View on GitHub

reading-notes

https://samahabujwaied.github.io/reading-notes/

Drawing text

The canvas rendering context provides two methods to render text:

A fill Text example

The text is filled using the current fillStyle.

function draw() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.font = '48px serif'; ctx.fillText('Hello world', 10, 50);}

The text is filled using the current strokeStyle.

function draw() {var ctx = document.getElementById('canvas').getContext('2d'); ctx.font = '48px serif'; ctx.strokeText('Hello world', 10, 50);}

Styling text

In the examples above we are already making use of the font property to make the text a bit larger than the default size. There are some more properties which let you adjust the way the text gets displayed on the canvas:

Applying styles and colors

color is a string representing a CSS <color>, a gradient object, or a pattern object. We’ll look at gradient and pattern objects later. By default, the stroke and fill color are set to black (CSS color value #000000).

Note: When you set the strokeStyle and/or fillStyle property, the new value becomes the default for all shapes being drawn from then on. For every shape you want in a different color, you will need to reassign the fillStyle or strokeStyle property.

A fill Style example

function draw() { var ctx = document.getElementById('canvas').getContext('2d'); for (var i = 0; i < 6; i++) { for (var j = 0; j < 6; j++) { ctx.fillStyle = 'rgb(' + Math.floo (255 - 42.5 * i) + ', ' + Math.floor(255 - 42.5 * j) + ', 0)'; ctx.fillRect(j * 25, i * 25 25, 25); } } }

A stroke Style example

function draw() { var ctx = document.getElementById('canvas').getContext('2d'); for (var i = 0; i < 6; i++) { for (var j = 0; j < 6; j++) { ctx.strokeStyle = 'rgb(0, ' + Math.floor(255 - 42.5 * i) + ', ' + Math.floor(255 - 42.5 * j) + ')'; ctx.beginPath(); ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, Math.PI * 2, true); ctx.stroke();}} }

Transparency

In addition to drawing opaque shapes to the canvas, we can also draw semi-transparent (or translucent) shapes. This is done by either setting the globalAlpha property or by assigning a semi-transparent color to the stroke and/or fill style. globalAlpha = transparencyValue

Drawing shapes with canvas

Drawing rectangles

  1. fillRect(x, y, width, height) Draws a filled rectangle.
  2. strokeRect(x, y, width, height) Draws a rectangular outline.
  3. clearRect(x, y, width, height) Clears the specified rectangular area, making it fully transparent.
Drawing a triangle

Moving the pen

Lines

Arcs

Quadratic Bezier curves

Cubic Bezier curves

Rectangles (Making combinations)

Path2D example

Basic usage of canvas