HTML - Canvas Element

> (World Wide) Web - (W3|WWW) > HyperText markup Language (HTML)

1 - About

The 2D Context provides objects, methods, and properties to draw and manipulate graphics on a canvas drawing surface.

Advertising

3 - Example: 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>

4 - Example: 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>

5 - 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

6 - Library

7 - Documentation / Specification

Advertising
web/html/canvas.txt ยท Last modified: 2019/02/09 11:29 by gerardnico