Skip to content

Instantly share code, notes, and snippets.

@lynxerzhang
Created March 31, 2017 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lynxerzhang/ac9b3a738b708fd1cd7363ddd05e320d to your computer and use it in GitHub Desktop.
Save lynxerzhang/ac9b3a738b708fd1cd7363ddd05e320d to your computer and use it in GitHub Desktop.
Simple HTML5 Motion
<canvas id ="canvas" width="300", height="200"></canvas>
//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();
body{
margin: 0px;
padding: 0px;
}
#canvas{
background-color:#333;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment