First steps with Canvas

Canvas is an HTML tag for graphics on an interactive drawing surface. Its use is very simple.

Indeed, you only need three things to use Canvas:

  1. HTML page with HTML document 5.
  2. "canvas" lighthouse.
  3. Some JavaScript code

1) HTML document 5

You must specify DOCTYPE in the first line of the page, which for HTML 5 has the following form:

<!DOCTYPE html>

2) Tag canvas

A tag must have the "id" attribute in order to be referenced in JavaScript code:

<canvas id="moncanevas" width="400" height="300"></canvas>  

This tag has no HTML content, except for a message that only appears in older browsers that do not recognize HTML 5. Exempli gratia:

<canvas id="moncanevas" width="400" height="300">
  Canvas n'est pas implémenté dans ce navigateur.
</canvas>   

3) Script in JavaScript

<canvas> content is dynamically defined by JavaScript code. For example, you can display a blue rectangle .

canvas = document.getElementById("moncanevas"); 
if (canvas.getContext)
{    
    context = canvas.getContext('2d'); 
}
function rectangle()
{
   context.fillRect(100,0,80,80);     
}  

The script will be started using the onload event associated with the <body> tag or window element.
This example creates the setCanvas () function and assigns it to onload:

function setCanvas()
{
  var canvas = document.getElementById("moncanevas"); 
  var context = canvas.getContext("2d");
  context.fillStyle = "blue"   
  context.fillRect(100,0,200,100);
}
window.onload=setCanvas;

The fillStyle attribute assigns the current color to the context, which will be the drawing objects. It can be assigned a color name, rgb or rgba code .
The fillRect method shows a rectangle filled with the current color, and for parameters - x, y, width, height.

Demo (Firefox, Chrome, Edge, Safari, Opera):

Canvas API Graphics Feature List

Look at this demo

See also