LearnFast.Ninja

Drawing line on canvas

If you want to draw lines in HTML page, you can do that in HTML5 with the canvas tag. In this tutorial you will see how to draw lines on the canvas tag with the help of JavaScript.

Step 1: Create the canvas tag:

<canvas id="myCanvas" width="300" height="300">

            Canvas not supported on your browser

</canvas>

 

Step 2: Create script tag after the canvas tag:

<script type="text/javascript">

 

</script>

 

Step 3: Get the canvas context:

var canvas = document.getElementById("myCanvas");

var canvasContext = canvas.getContext("2d");

 

Step 4: Choose first point by moving the canvas pointer to that point:

canvasContext.moveTo(10, 10);

 

Step 5: Choose the second point of the line and stroke the line to the screen

canvasContext.lineTo(80, 80);

canvasContext.stroke();

 

Result:



Complete code:

<!DOCTYPE html>

<html>

<head>

    <title></title>

</head>

<body>

    <canvas id="myCanvas" width="300" height="300">

        Your browser does not support the HTML5 canvas tag.

    </canvas>

 

    <script type="text/javascript">

        var canvas = document.getElementById("myCanvas");

        var canvasContext = canvas.getContext("2d");

        canvasContext.moveTo(10, 10);

        canvasContext.lineTo(80, 80);

        canvasContext.stroke();

    </script>

</body>

</html>


Tags

javascript

canvas line stroke