JSFiddle - React, Tailwind, and code Playground

by Peter Scargill

HTML

<canvas height="350" width="350" id="back" style="z-index: 1"></canvas>
<canvas height="350" width="350" id="front" style="z-index: 2"></canvas>

CSS

canvas {
      position: absolute;
      border: 1px solid black;
    }

JavaScript

var needle = new Image();
var centre = new Image();
needle.src = "http://www.scargill.net/things/needles/redCurvedNeedle.png";
centre.src = "http://www.scargill.net/things/needles/greyCarvedCentre.png";
var needleWidth = 1;
var degrees = 0;

canvas = document.getElementById("front");
ctx = canvas.getContext("2d");
cX = Math.floor(canvas.width / 2);
cY = Math.floor(canvas.height / 2);
dX = cX / 175; // divisor for centrepiece sizing
dY = cY / 175;

backcanvas = document.getElementById("back");
ctx2 = backcanvas.getContext("2d");

// Draw bottom layer once only
ctx2.save;
ctx2.font = "bold " + String(Math.floor(cX / 8)) + "px Helvetica";
ctx2.textAlign = 'center';
ctx2.fillStyle = '#000000';
ctx2.fillText("Text on bottom layer", cX, cY, cX);
ctx2.restore;

// the following are merely caclulated here to save calculating them for every angle in the draw() 
// routine which seems wasteful especially as it is interpreted
var ne1=(canvas.width / 7) - (canvas.width / 4);
var ne2= -(canvas.height * needleWidth / 80);
var ne3=(canvas.height / 2);
var ne4=(canvas.width * needleWidth / 40);
var kn1=(0 - (centre.height / 4)) * dX;
var kn2=(0 - (centre.width / 4)) * dY;
var kn3= (centre.height / 2) * dX;
var kn4=(centre.width / 2) * dY;

// every 10 ms, clear the top layer and draw a new needle at 0.5 degrees intervals and the knob
setInterval(draw, 10);

function draw() { // this gets called repeatedly.
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.save();
  ctx.beginPath();
  ctx.translate(cX, cY);
  ctx.rotate(degrees * (Math.PI / 180));
  // shadow on lines??
  ctx.shadowBlur = 4;
  ctx.shadowColor = "rgba(0,0,0,0.2)";
  ctx.shadowOffsetX = 5 * dX;
  ctx.shadowOffsetY = 5 * dX;
  ctx.drawImage(needle, ne1,ne2,ne3,ne4);
  // Restore the previous drawing state
  ctx.restore();
  degrees += 0.5;
  if (degrees > 359) degrees = 0;
  ctx.save();
  ctx.beginPath();
  ctx.translate(cX, cY);
  // draw the centre bit then restore the previous drawing state
 ...