START-STOP MOTION
To start an HTML5 Canvas animation, we can can continually request a new animation frame, and to stop the HTML5 Canvas animation, we can simply not request a new animation frame.
by bhupendra negi
May 15, 2014
HTML
<canvas width = "400" height = "200" id = "myCanvas">
NO browser suppport for canvas
</canvas>
<input type = "button" value = "GO !" id = "start"/>
CSS
canvas {
border: 1px solid blue;
}
JavaScript
var strbtn = document.getElementById("start");
strbtn.addEventListener("click",ongo,false);
function drawRectangle(myRect,context)
{
context.beginPath();
context.fillStyle = "yellow";
context.rect(myRect.x,myRect.y,myRect.width,myRect.height);
context.lineWidth = 5;
context.fill();
context.strokeStyle = "black";
context.stroke();
}
function animate(myRectangle, canvas, context, startTime)
{
var time = (new Date()).getTime() - startTime;
console.log("time elapsed :" + time);
var speed = 100;
// distance = speed*time
var newX = speed*time/1000 // convert ms -- s
//changing x position of rectangle;
if(newX < canvas.width - myRectangle.width) {
myRectangle.x = newX;
//clear canvas for new frame
context.clearRect(0, 0, canvas.width, canvas.height);
// drawing new rectangle frame
drawRectangle(myRectangle,context);
requestAnimationFrame(function() {
animate(myRectangle, canvas, context, startTime);
});
}
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
//intial configuration of rectangle
var myRectangle = {
x: 0,
y: 75,
width: 100,
height: 50,
borderWidth: 5
};
drawRectangle(myRectangle, context);
// on GO click animation starts
function ongo()
{
var startTime = (new Date()).getTime();
console.log(startTime);
animate(myRectangle, canvas, context, startTime);
}