<canvas id="tutorial" width="150" height="150"></canvas>
<script>
var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');
// your code here
</script>
<canvas id="tutorial" width="150" height="150"></canvas>
<script>
var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
// your code here
</script>
See this blog post on smart animating with Canvas.
function render() {
// your code here
};
window.requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback, element) {
window.setTimeout(callback, 16);
};
(function animloop(){
requestAnimFrame(animloop);
render();
})();
Here's an example of a basic full screen, animated canvas.
// clear the canvas
ctx.fillStyle = "#fff"
ctx.fillRect(0,0,width,height);
Canvas also has methods for linear and radial gradients.
// horizontal hue gradient
for (var i = 0; i < width; i++) {
ctx.fillStyle = "hsl(" + i + ",50%,50%)";
ctx.fillRect(i,0,1,height);
}
// horizontal hue, vertical saturation gradient
for (var i = 0; i < 360; i++) {
for (var j = 0; j < 400; j++) {
ctx.fillStyle = "hsl(" + i + "," +
Math.round(100*j/400) + "%,50%)";
ctx.fillRect(i,j,1,1);
}
}
Use this example in animate mode:
// circular motion
var time = Date.now() / 1600;
var x = Math.sin(time);
var y = Math.cos(time);
// fade canvas
ctx.fillStyle = "rgba(0,0,0,0.2)"
ctx.fillRect(0,0,width,height);
// scale and center
var i = width * ((1+x)/2);
var j = height * ((1+y)/2);
// draw dot
ctx.fillStyle = "#fff";
ctx.fillRect(i,j,2.5,2.5);
See this tutorial for examples of translating, rotating and scaling the canvas.