HTML5 Game - Canvas Line

Introduction

This example will show you how to draw a simple straight line.

Follow these steps to draw a diagonal line:

Demo

ResultView the demo in separate window

<html>
    <head>
        <script>
            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
                context.lineWidth = 10;// set the line width to 10 pixels
                context.strokeStyle = "blue";// set the line color to blue
                context.moveTo(50, canvas.height - 50);// position the drawing cursor
                context.lineTo(canvas.width - 50, 50);// draw the line
                context.stroke();// make the line visibile with the stroke color
            };//from   w w w . jav  a2  s  . c om
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

In the code above, we waited for the page to load before trying to access the canvas tag by its ID via the window.onload initializer.

Once the page loads, we can access the canvas DOM element with document.getElementById().

Then we defined a 2D canvas context by passing 2d into the getContext() method of the canvas object.

When drawing an element, such as a path, sub path, or shape, the styles can be set at any time, either before or after the element is drawn.

The style must be applied immediately after the element is drawn.

We can set the width of our line with the lineWidth property.

We can set the line color with the strokeStyle property.

strokeStyle is like the colored marker and lineWidth is its tip thickness.

To position the marker onto the canvas we can the moveTo() method:

context.moveTo(x,y); 

The canvas context has a drawing cursor.

The moveTo() method moves the cursor to new point.

The coordinates in the top-left corner of the canvas are (0,0), and the coordinates in the bottom-right corner are (canvas width, canvas height).

After positioning the drawing cursor, we can draw the line using the lineTo() method by defining the coordinates of the line's end point:

context.lineTo(x,y); 

Finally, to make the line visible, we can use the stroke() method.

The default stroke color is black.

You can follow the following steps to draw a line

  • Style your line with lineWitdh and strokeColor
  • Position the canvas context using moveTo()
  • Draw the line with lineTo().
  • Make the line visible using stroke().

Related Topics