View on GitHub

reading-notes

What is HTML Canvas?

element is used to draw graphics, on the fly, via scripting (usually JavaScript).

Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

The <canvas element must have an id attribute so it can be referred to by JavaScript.

The width and height attribute is necessary to define the size of the canvas.

id

HTML Canvas Drawing

drawing

HTML Canvas Coordinates

The HTML canvas is a two-dimensional grid, The upper-left corner of the canvas has the coordinates (0,0).

Draw a Line

To draw a straight line on a canvas, use the following methods:

To actually draw the line, you must use one of the “ink” methods, like stroke().

3

Draw a Circle

4

HTML Canvas Gradients

Gradients can be used to fill rectangles, circles, lines, text, etc. Shapes on the canvas are not limited to solid colors.

There are two different types of gradients:

The addColorStop() method specifies the color stops, and its position along the gradient. Gradient positions can be anywhere between 0 to 1.

Using createLinearGradient()

Create a linear gradient.

5

Using createRadialGradient():

Create a radial/circular gradient.

6

HTML Canvas Text

Using fillText()

Set font to 30px “Arial” and write a filled text on the canvas.

7

Using strokeText()

Set font to 30px “Arial” and write a text, with no fill, on the canvas:

8

HTML Canvas Images

To draw an image on a canvas, use the following method:

9