2D Canvas Example
Simple example of 2D canvas
by Quique Fdez Guerra
HTML
<button id="play">play animation</button>
<button id="stop">stop animation</button>
JavaScript
(function(g){
// ugly code for an example :/
g.can = document.createElement("canvas");
can.width = 800;
can.height = 600;
document.body.appendChild(can);
g.ctx = can.getContext('2d');
// Decoration
ctx.globalAlpha = 0.6;
ctx.fillStyle = 'red';
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
// Rects
ctx.fillRect(0, 0, 50, 50);
ctx.strokeRect(60, 60, 50, 50);
ctx.clearRect(45, 45, 20, 20);
// Arc
ctx.beginPath(); // Empiezo un path
/// x, y, radio, anguloIn, anguloFin, antiClk
ctx.arc(140, 80, 50, 0, rad(90), false);
ctx.stroke(); // Pinta
// Irregular
ctx.beginPath();
ctx.strokeStyle = 'magenta';
ctx.arc(250, 90, 50, 0, rad(90), false);
ctx.arc(240, 80, 50, 0, rad(90), false);
ctx.stroke();
// Irregular 2
ctx.beginPath();
ctx.strokeStyle = 'green';
ctx.arc(80 + 250, 90, 50, 0, rad(90), false);
ctx.moveTo(80 + 250 + 40, 90 - 10);
ctx.arc(80 + 240, 80, 50, 0, rad(90), false);
ctx.stroke();
// Image
drawImage('http://www.windows8core.com/wp-content/plugins/simple-forum/styles/icons/default/custom//Windows-8-logo-300x300.png', 0, 150);
// Animation
g.timmer,g.color,g.x = 0, g.v, g.vinit = 4, g.right = true; //v en px/sec
g.colors = ['red', 'green', 'orange', 'pink'];
document.querySelector('#play').addEventListener('click', start);
document.querySelector('#stop').addEventListener('click', stop);
})(window);
// Functions
function rad(deg) {
return deg*Math.PI/180;
}
function drawImage(src, x, y, width, height) {
var img = new Image();
img.src = src;
img.onload = function(){
ctx.drawImage(img, x, y, width || img.width, height || img.height);
};
}
function drawTest(color) {
ctx.save();
ctx.fillStyle = color;
ctx.fillRect(x, 200, 60, 60);
ctx.restore();
}
function animation() {
update();
draw();
timmer = requestAnimationFrame(animation);
}
function update() {
v =...