Dorokhov.codes

Canvas

Adding a canvas element to the HTML:

<canvas id="canvas" width="500" height="500"></canvas>

Getting a canvas DOM object:

var canvas = document.getElementById("canvas");

Drawing context

Drawing context is a JavaScript object that has methods and properties by which we can draw on a canvas.

Getting a drawing context:

var ctx = canvas.getContext("2d");

Choosing a color

List of all named colors.

ctx.fillStyle = "Red"; // filling
ctx.strokeStyle = "Green"; // outlines

Drawing a rectangle

ctx.fillRect(0, 0, 100, 100);
// 0,0 - top left corner coordinates.
// 100, 100 - width and height of the rectangle

Drawing a rectangle outline

ctx.strokeRect(10, 10, 100, 20);
// 0,0 - top left corner coordinates.
// 100, 100 - width and height of the rectangle

Line width for outlines:

ctx.lineWidth = 4;

Drawing a path

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.strokeStyle = "Turquoise";
ctx.lineWidth = 4;
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(60, 60);
ctx.moveTo(60, 10);
ctx.lineTo(10, 60);
ctx.stroke();

If you need to fill in a closed path, instead of just stroke it, use fill instead of stroke.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "Blue";
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(100, 60);
ctx.lineTo(130, 30);
ctx.lineTo(160, 60);
ctx.lineTo(160, 100);
ctx.lineTo(100, 100);
ctx.fill();

Circles

Method arc(x, y, radius, angle_from, angle_to, counterclockwise)

ctx.lineWidth = 2;
ctx.strokeStyle = "Green";

// Quater:
ctx.beginPath();
ctx.arc(50, 50, 20, 0, Math.PI / 2, false);
ctx.stroke();

// Half:
ctx.beginPath();
ctx.arc(100, 50, 20, 0, Math.PI, false);
ctx.stroke();

// Full circle:
ctx.beginPath();
ctx.arc(150, 50, 20, 0, Math.PI * 2, false);
ctx.stroke();

Clearing

ctx.clearRect(0, 0, 200, 200);

Text

// text string, x, y
ctx.fillText("Hello world!", 50, 50);

// base line
ctx.textBaseline = "top"; // top, bottom or middle. bottom is default.
ctx.fillText("Hello world!", 50, 50);

// horizontal align
ctx.textAlign = "left"; // left, center or right.


// Font:
ctx.font = "20px Courier";
ctx.font = "24px Comic Sans MS";
ctx.font = "18px Arial";