HTML5 Canvas: Drawing a line in the canvas

This entry is part 2 of 17 in the series HTML5 Canvas

To draw on the canvas from JavaScript, you first must grab the context of the canvas id you want to draw on.

To do this, your script will get the canvas element by id and then use getContext to grab a reference to the canvas element’s two-dimensional context.

<!DOCTYPE html>
<html lang='en'>
    <meta charset='utf-8'>
    <title> Canvas Line</title>
        canvas {
            border: 1px solid #000;
<canvas id='myCanvas' width='640' height='480'></canvas>
    var canvas = document.getElementById('myCanvas').getContext('2d');
    canvas.moveTo(0, 0);
    canvas.lineTo(640, 480);


Series Navigation<< HTML5 Canvas: Introduction
HTML5 Canvas: Canvas tools >>

Leave a comment

Leave a Reply