Canvas Demo - Oscillating Rectangle
by Ron Eaglin
HTML
<div id="calledFunction">Ready, set, go....</div>
<hr/>
<canvas id="myCanvas" width="600" height="230"></canvas>
<hr />
JavaScript
var animateCounter = 1;
var myRectangle = {
x: 50,
y: 50,
width: 50,
height: 50,
borderWidth: 2
};
function drawRectangle(myRectangle, context) {
// starts the drawing
context.beginPath();
// this defines the rectangle
context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = myRectangle.borderWidth;
context.strokeStyle = 'blue';
// this draws the rectangle
context.stroke();
}
// You are either going to get an animation frame
// or the program will time out
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
// The actual function that animates the rectangle
function animate(myRectangle, canvas, context, startTime) {
// update time
var time = (new Date()).getTime() - startTime;
document.getElementById("calledFunction").innerHTML = "Animate called: " + animateCounter++ + " Time Value: " + time;
var amplitudeX = 225;
var amplitudeY = 75;
// in ms calculates position of rectangle
var period = 2000;
if (orientation == "horizontal")
{
var centerX = canvas.width / 2 - myRectangle.width / 2;
var nextX = amplitudeX * Math.sin(time * 2 * Math.PI / period) + centerX;
myRectangle.x = nextX;
}
else
{
var centerY = canvas.height / 2 - myRectangle.height / 2;
var nextY = amplitudeY * Math.sin(time * 2 * Math.PI / period) + centerY;
myRectangle.y = nextY;
}
...