Basics of Canvas

<canvas></canvas>

Triangle

context.beginPath();
context.moveTo(100,50);
context.lineTo(200,75);
context.lineTo(200,25);
// Any open shapes are closed automatically when fill() is called. No need to call closePath()
context.fill(); 

arc(x,y,radius,startAngle,endAngle,antiClockwise)

arcTo(x1,y1,x2,y2,radius)

The arc is tangential to both segments

        context.beginPath();
        context.strokeStyle = 'black';
        context.lineWidth = 5;
        // 1st Segment (200,20) & (200,130)
        // 2nd segment (50,20) & (200,130)
        context.moveTo(200, 20);
        context.arcTo(200,130, 50,20, 40);
        context.stroke();

rect(x,y,width,height)

context.beginPath();
context.rect(250,10,50,50);
context.fill();

fillText(text,x,y[,maxWidth])

context.font = '12px serif';
context.fillText('(100,100)',100,100);

Loading image

context.drawImage(image,x,y);
context.drawImage(image,x,y,width,height);// For scaling image
// Geting somepart of the image loading it on to the canvas
drawImage(image,sourceX,sourceY,destinationX,destinationY,width,height);


// Example
var canvasImg = document.getElementById('canvas_image');
var contextImg = canvasImg.getContext('2d');

var img = new Image();
img.addEventListener('load',function(){
    contextImg.drawImage(img,0,0,300,150);
},false);
img.src = "url_of_image";

Note: false(default) - The event handler is executed in the bubbling phase. WHen true executed in the capturing phase.

Transformations

save()

saves the entire state of the canvas.

restore()

restores the most recently saved canvas state.

States stored are

translate(x,y)

rotate(angle)

scale(x, y)

To create Cartesian coordinate system with the origin in the bottom left corner

        var canvas_scale = document.getElementById('canvas_scale');
        var ctx = canvas_scale.getContext('2d');
        ctx.save();
        ctx.scale(10, 3);
        ctx.fillRect(1, 10, 10, 10);
        ctx.restore();

        ctx.fillStyle = 'rgba(200,0,0,0.5)';
        ctx.fillRect(1, 10, 10, 10);

        // mirror horizontally
        ctx.scale(-1, 1);
        ctx.font = '48px serif';
        ctx.fillText('INDIA', -135, 120);