Getting started with HTML5 canvas

HTML5 canvas element is a simple HTML tag. It allows dynamic and script-able rendering of 2D and bitmap images. Canvas consists of a drawable region defined in HTML code with height and width attributes. Javascript code is used to access the area through a full set of drawing functions.
In this tutorial I'm going to explain the basics of canvas element and how it can be used to draw a line. So in order to use the canvas element , you'll need to place the canvas element somewhere inside your html.
<!DOCTYPE HTML>
<html>
  <head>
    <script>
      window.onload = function() {
        var canvas = document.getElementById("canvas_area");
        var context = canvas.getContext("2d");
             //code here 
     
      };

    </script>
  </head>
  <body>
    <canvas id="canvas_area" width="600" height="300"></canvas>
  </body>
</html>
The code above will be the base template for all of your future HTML5 Canvas projects. We can define the height and width of the canvas tag using the height and width attributes, just like we would with any other HTML tag. Inside the initializer function we can access the canvas DOM object, and then get a 2-d context using the getContext() method.

How to draw a line

<!DOCTYPE HTML>
<html>
  <head>
   <style>
    #canvas_area{
    border:solid 1px #999;
    }
   </style>
    <script>
      window.onload = function() {
        var canvas = document.getElementById("canvas_area");
        var context = canvas.getContext("2d");
        context.beginPath();
        context.moveTo(100,150);
        context.lineTo(400,250);
        context.stroke();
      };

    </script>
  </head>
  <body>
    <canvas id="canvas_area" width="600" height="300"></canvas>
  </body>
</html>

A little explanation

beginPath() -  defines a new drawing path.
moveTo() -   creates a new subpath for the given point. This point becomes the new context point. You can think of the moveTo() method as a way to position your drawing cursor.
lineTo() -  draws a line from the context point to the given point.
stroke() -  assigns a color to the line and makes it visible. Unless otherwise specified, the default stroke color is black.



1 comment:

  1. I never thought I will come in contact with a real and potential hacker until I knew   brillianthackers800 at Gmail and he delivered a professional job,he is intelligent and understanding to control jobs that comes his way
    You can message on his number +1(385) 2501115,
    Contact him and be happy

    ReplyDelete