const wheelImg = new Image;
wheelImg.src = "https://www.freeiconspng.com/uploads/car-wheel-png-image-free-download--car-wheel-png-image-free--11.png";
canvas.width = innerWidth - 30;
canvas.height = innerHeight - 40;
const ctx = canvas.getContext("2d");
const wheelScale = 0.4; // scales the wheels
const rotateCount = 100; // frames (@60 per second)
var activeWheelCount = 0; // to track if any wheels are active
// when the image has loaded set up click events and draw the first frame
wheelImg.addEventListener("load",() => {
requestAnimationFrame(mainLoop)
clockwiseBtn.addEventListener("click",() => wheels[0].start(Math.PI / 2));
antiClockwiseBtn.addEventListener("click",() => wheels[1].start(-Math.PI / 2));
}
,{once:true}
);
// defines a single wheel
const wheel = (x,y,rot) => ({
x,y,rot,
rotTarget: rot,
counter: 0,
start(ang) { // command a wheel to turn
if (!this.counter ) { // make sure not already turning
this.counter = rotateCount;
this.rotTarget += ang;
if (!activeWheelCount) { requestAnimationFrame(mainLoop) } // start the
// animation is no wheel
// is active
activeWheelCount ++;
}
},
update() { // update the wheel animation counter
this.counter += this.counter > 0 ? -1 : 0;
if (this.counter === 0) { this.rot = this.rotTarget }
else { activeWheelCount += 1 } // count this wheel as an active wheel
},
draw() { // draw the wheel
const r = (1 - (this.counter / rotateCount)) * (this.rotTarget - this.rot) + this.rot;
ctx.setTransform(wheelScale, 0, 0, wheelScale, this.x, this.y);
ctx.rotate(r);
ctx.drawImage(wheelImg, -wheelImg.width / 2, -wheelImg.height / 2);
}
});
const wheels = [wheel(90,80, 0), wheel(350,80,0)]; // create two wheels
function mainLoop() { // animates wheels
activeWheelCount = 0;
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
wheels.forEach(wheel => wheel.update());
wheels.forEach(wheel => wheel.draw());
if (activeWheelCount) {
requestAnimationFrame(mainLoop);
}
}
#canvas {
border:solid 1px black;
position:absolute;
top:30px;
left:0px;
}
<canvas id="canvas"></canvas>
<button id='clockwiseBtn'>Wheel1</button>
<button id='antiClockwiseBtn'>Wheel2</button>