Adding and Drawing on Canvas in HTML5
You can add canvas to your HTML5 page with the help of HTML5 tag called canvas. See example below
<canvas height="100" width="100"> </canvas>
This HTML5 element can have attributes just like any older HTML tag. In order to put a border around this canvas, we’ll need to add style to this tag
<canvas height="100" width="100" style="border: 1px solid;"> </canvas>
HTML5 canvas needs to be identified in order for our JavaScript find canvas as object on our page.
<canvas id="sample" height="100" width="100" style="border: 1px solid;"> </canvas>
Let’s draw something on our canvas in order to make it useful to our users. We’ll draw a simple line for this example.
<script>
function drawLine()
{
var myCanvas = document.getElementById('canvas');
var myContext = canvas.getContext('2d');
myContext.beginPath();
myContext.moveTo(30, 90);
myContext.lineTo(90, 30);
myContext.stroke();
}
window.addEventListener("load", drawLine, true);
</script>
This code is not overly complicated if you already know JavaScript. However, if you are new to JavaScript then you may read about it online. In brief, we set two points on our canvas and called on stroke() method to draw a line between two points.