Falcon80 Logo
Defining a canvas element in HTML

The canvas element can be defined using the <canvas></canvas> tag inside HTML. Within the tag, you can specify the length and width of the element. Both length and width should be positive integers and if now specified, default to 300 px and 150 px respectively. You can also have an id for each canvas element (you can have multiple canvas areas on the same HTML page) which will show up in DOM. You can then access the canvas element from javascript using the canvas id.

<canvas id = "myCanvas" length = "900" width = "400"> </canvas>

You can place the canvas anywhere on the page. In the following example, it is placed at the beginning of a HTML page that has no other formatting or content.

<html>
<head>
<title> working with HTML5 Canvas</title?
</head>
<body>
<canvas id="myCanvas" width="900" height="500"></canvas><br>
</body>
</html>

We can now access this canvas from javascript. In the following example, I am calling the function init(), from where we will access the canvas element. The canvas element can be accessed using the getElementById() method.

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

Once you successfully grab the element, you have to get the context of the canvas using the getContext() method. All the canvas methods and attributes are implemented in the context. So it is essential to get hold of it first before you start drawing anything on the canvas. In this tutorial, we will be working on the 2-D context. So we will pass 3d as a parameter for the getContext() method. The 3d context is still in the experimental stage.

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

Now that you have the context, you can call the canvas methods and attributes implemented in the conext. The following code will draw a rectangle around the canvas space you have defined.
HTML Code
<html>
<head>
  <script type="application/javascript">
function init() {
var canvas = document.getElementById("myCanvas");
if (canvas.getContext) {

var ctx = canvas.getContext("2d");
ctx.strokeRect(0,0,900,500);
}
}
  </script>
  <title>Translating an image on canvas </title>
</head>
<body onload="init();">
<canvas id="myCanvas" width="900" height="500"></canvas><br>
</body>
</html>
 
Try Code