Prev Demo
HTML5
>
Canvas Animation
Next Demo
Write code here
J
|
B
|
A
<!DOCTYPE html> <html> <head> <title>Demo</title> </head> <body> <h1 style="color:green;">Moves the rectangle animated frame towards right</h1> <canvas id="myCanvas" width="600" height="300"></canvas> <script> window.requestAnimFrame = (function (callback) { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); }; })(); function drawRectangle(myRectangle, context) { context.beginPath(); context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height); context.fillStyle = 'blue'; context.fill(); context.lineWidth = myRectangle.borderWidth; context.strokeStyle = 'red'; context.stroke(); } function animate(myRectangle, canvas, context, startTime) { var time = (new Date()).getTime() - startTime; var linearSpeed = 100; var newX = linearSpeed * time / 1000; if (newX < canvas.width - myRectangle.width - myRectangle.borderWidth / 2) { myRectangle.x = newX; } context.clearRect(0, 0, canvas.width, canvas.height); drawRectangle(myRectangle, context); requestAnimFrame(function () { animate(myRectangle, canvas, context, startTime); }); } var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var myRectangle = { x: 20, y: 50, width: 200, height: 100, borderWidth: 10 }; drawRectangle(myRectangle, context); setTimeout(function () { var startTime = (new Date()).getTime(); animate(myRectangle, canvas, context, startTime); }, 1000); </script> </body> </html>
Note: We DO NOT save your trial code in our database.
Output