About

This page is about the canvas html element and shows you some examples.

Note before going on the examples: On a canvas drawing surface, the 2D Canvas Context is the API and provides:

  • objects,
  • methods,
  • and properties to draw and manipulate graphics.

Example

Drawing the origin

function graphAxes(width, height) {

    ctx.beginPath();
    ctx.strokeStyle = "black";
    // X axis
    ctx.moveTo(0, 0);
    ctx.lineTo(width, 0);
    // Y axis
    ctx.moveTo(0, 0);
    ctx.lineTo(0,height);
    ctx.stroke();
}

// Main Global Scope
canvas = document.getElementById("graph");
ctx = canvas.getContext("2d");
graphAxes(600,300);
<canvas id="graph" width="600" height="300"></canvas>
  • Output: the 2 axis

How to create a Function Grapher

function graphFunction(graph, func, color) {

    // A point every 4 pixels
    var dx = 4;
    
    // Properties
    ctx.strokeStyle = color;

    // Begin Path Graphing
    ctx.beginPath();
    for (var x = graph.xMin; x <= graph.xMax; x = x+dx) {
        y = graph.yScale * func(x / graph.xScale);
        if (x == graph.xMin) {
            ctx.moveTo(graph.x0 + x, graph.y0 - y);
        }
        else ctx.lineTo(graph.x0 + x, graph.y0 - y);
    }
    ctx.stroke();
}

function graphAxes(graph) {

    ctx.beginPath();
    ctx.strokeStyle = "black";
    // X axis
    ctx.moveTo(0, graph.y0);
    ctx.lineTo(graph.width, graph.y0);
    // Y axis
    ctx.moveTo(graph.x0, 0);
    ctx.lineTo(graph.x0, graph.height);
    ctx.stroke();
}

// Main Global Scope
canvas = document.getElementById("graph");
ctx = canvas.getContext("2d");

// Graph Properties
var graph = {
    x0: .5 + .5 * canvas.width,  // x0 pixels from left to x=0
    y0: .5 + .5 * canvas.height, // y0 pixels from top to y=0
    get xMax(){ return canvas.width - this.x0},
    get xMin(){ return - this.x0},
    xScale: 40,                 // Number of pixels from x=0 to x=1
    yScale: 100,                 // Number of pixels from y=0 to y=1
    width: canvas.width,
    height: canvas.height
};

// Graph

// The axes
graphAxes(graph);

// The first Function
var sin = (x) => Math.sin(x);
graphFunction(graph, sin, "blue");

// The second Function
var cos = (x) => Math.cos(x);
graphFunction(graph, cos, "red");
<canvas id="graph" width="600" height="300"></canvas>

How to download / export canvas content as image

let download = function(selector){
  let canva = document.querySelector(selector);
  let link = document.createElement('a');
  link.download = 'filename.png';
  link.href = canva.toDataURL()
  link.click();
}

Export format

Browsers canvas implementation only generate raster images, and don't help with SVG or PDF. https://github.com/bokeh/bokeh/issues/538#issuecomment-157931426

Library

Documentation / Specification