Easy jQquery Plugins

TechnoPlugin

Let us create an example to draw some lines with different styles in a HTML5 canvas.

    <!DOCTYPE HTML>
    <html>
      <head>
        <style>
          body {
            margin: 0px;
            padding: 0px;
          }
            #myCanvas {
                border:1px solid #000000;
            }
        </style>
      </head>
      <body>
        <canvas id="myCanvas" width="400" height="350"></canvas>
        <script>
            var canvas = document.getElementById('myCanvas');
            var context = canvas.getContext('2d');

            //create a basic line
            context.beginPath();
            context.moveTo(50, 100);
            context.lineTo(250, 50);
            context.stroke();

            // set line color
            context.beginPath();
            context.moveTo(50, 175);
            context.lineTo(260, 125);
            context.lineWidth = 5;
            context.strokeStyle = '#30cd74';
            context.stroke();

            //set the width of line
            context.beginPath();
            context.moveTo(50, 250);
            context.lineTo(250, 200);
            context.lineWidth = 15;
            context.strokeStyle = '#34495e';
            context.stroke();

            // round line cap 
            context.beginPath();
            context.moveTo(50, 325);
            context.lineTo(250, 275);
            context.lineWidth = 20;
            context.strokeStyle = '#d0000f';
            context.lineCap = 'round';
            context.stroke();

        </script>
      </body>
    </html>  

The above code will produce the following result

To draw a basic line following methods are used:

  • beginPath() - Initializing the path context object to define a path
  • moveTo() - Defines the starting coordinates of line
  • lineTo() - Defines the ending coordinates of line
  • stroke() - Created a stroke in the defined path

To define the color of line the strokeStyle property of the context can be assigned with the desired colour.
To define the with of the line lineWidht property of the context can be assigned with the desired width.
To add a cap to a line lineCap property can be used with three cap styles: butt, round, or square.

Close
loading
  Contact Submit plugin