//class AnimLib inspired by bit101's js lib (write with es6) class AnimLib { constructor(renderCallback, fps = 60){ this.renderCallback = renderCallback; this.fps = fps; } start(){ if (!this.running) { this.running = true; this.render(); } this.shouldKill = false; } stop(){ this.shouldKill = true; } toggle(){ if (this.running) { this.stop(); } else { this.start(); } } render(){ if(this.shouldKill) { this.shouldKill = false; this.running = false; } if (this.running) { this.renderCallback(); setTimeout(() => requestAnimationFrame(() => this.render()), 1000 / this.fps); } } } const degreeToRadius = Math.PI / 180; const canvas = document.getElementById("canvas"); const context = canvas.getContext("2d"); const canvasWidth = canvas.width; const canvasHeight = canvas.height; const rectWidth = 100; const rectHeight = 10; let rotation = 0; let mouse = {x:0, y:0}; canvas.addEventListener("mousemove", (event) => { mouse.x = event.pageX - canvas.offsetLeft; mouse.y = event.pageY - canvas.offsetTop; }); const canvasHalfHeight = canvasHeight * 0.5|0; const canvasHalfWidth = canvasWidth * 0.5|0; const rectHalfWidth = rectWidth * 0.5|0; const rectHalfHeight = rectHeight * 0.5|0; let render = () => { context.clearRect(0, 0, canvasWidth, canvasHeight); rotation = Math.atan2(mouse.y - canvasHalfHeight, mouse.x - canvasHalfWidth); context.save(); context.translate(canvasHalfWidth, canvasHalfHeight); context.rotate(rotation); context.fillStyle = "yellow"; context.fillRect(-rectHalfWidth, -rectHalfHeight, rectWidth, rectHeight); context.restore(); } //this motion inspired by the html5 animation with javascript (by Billy Lamberta & Keith Peters) let ns = new AnimLib(render, 60); ns.start();