Drawing a line

When learning how to draw with the HTML5 canvas for the first time, most people are interested in drawing the most basic and rudimentary element of the canvas. This recipe will show you how to do just that by drawing a simple straight line.

Drawing a line

How to do it...

Follow these steps to draw a diagonal line:

  1. Define a 2D canvas context and set the line style:
    window.onload = function(){ // get the canvas DOM element by its ID var canvas = document.getElementById("myCanvas"); // declare a 2-d context using the getContext() method of the // canvas object var context = canvas.getContext("2d"); // set the line width to 10 pixels context.lineWidth = ...

Get HTML5 Canvas Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.