code prettify

Thursday, 20 November 2014

How to draw a triangle using Canvas?

Canvas is basically a space in the web page where you draw graphics using javascript. Everything on a canvas is all about canvas.

So to start, lets have a canvas space over a 600 x 400 pixel area.

<canvas width="600" height="400">

The next thing we need to do is get a reference to the canvas element and get a context reference to it. Context is basically an object with methods and properties that allows us to draw on the canvas.

To draw a triangle, we basically have to start at a point and proceed along a line then move on to another point tracing along the path as we do so. The basic point is to first create a path and then stroke or fill it, so as to make it visible.

Below is the code to draw a triangle on a canvas:

    // Get dom reference to canvas element
    var canvas = document.getElementsByTagName("canvas")[0];

    // Get context reference to canvas
    var context = canvas.getContext("2d");

    // Begin a path with beginPath() method
    context.moveTo(100, 150);

    // Traces a line path from current point to specified point
    context.lineTo(250, 75);
    context.lineTo(125, 30);

    // Closes the path by joining from current point to point where
    // path began first
    context.lineWidth = 5; // Sets the line width

    // Make the path visible by stroking it

    // Fill inside of the closed path structure with color
    context.fillStyle = "red";

Click here to see a demo.

No comments:

Post a Comment