View on GitHub

reading-notes

Basic usage of canvas


<canvas id="tutorial" width="150" height="150"></canvas>

NOTE :the canvas will initially be 300 pixels wide and 150 pixels high if no specified attributs added

To display something in the canvas , a script first needs to access the rendering context and draw on it. The <canvas> element has a method called getContext(), used to obtain the rendering context and its drawing functions.


var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');

Drawing shapes with canvas

# Drawing paths

- First, you create the path. `beginPath()`
- use drawing commands to draw into the path. `moveTo` `lineTo`
- stroke or fill the path to render it. `stroke()` `fill()`

# Applying styles and colors

- fillStyle : Sets the style used when filling shapes.
```javascript

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.floor(255 - 42.5 * i) + ', ' +
                       Math.floor(255 - 42.5 * j) + ', 0)';
      ctx.fillRect(j * 25, i * 25, 25, 25);
    }
  }
}


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();
      }
    }
  }

# Drawing text

Styling text