This is a guide of how to use HTML 5 Canvas, as well as some JavaScript/css tricks to enable drawing on top of a web page. To see the result of this tutorial, open http://permadi.com/blog/?p=383.
Canvas introduction is covered here and here.
You do not have to create a canvas object.
[code]&lt;<span class="start-tag">style</span><span class="attribute-name"> type</span>=<span class="attribute-value">"text/css"</span>&gt; canvas { border: 2px solid #000; float: left; margin-right: 20px; margin-bottom: 20px; } &lt;/style&gt; [/code]
See https://developer.mozilla.org/samples/canvas-tutorial/2_1_canvas_rect.html for more details.
[code]document.createElement('canvas');[/code]
To specify the dimensions, you should set the Canvas's width and height, as well as the style's width and height. If you only specifies the style width and height, then the canvas will be stretched to fit the parent's (container's) div.
[code] myCanvas=document.createElement('canvas'); myCanvas.style.width = containerDiv.offsetWidth+"px"; myCanvas.style.height = containerDiv.offsetHeight+"px"; // You must set this otherwise the canvas will be streethed to fit the container myCanvas.width=containerDiv.offsetWidth; myCanvas.height=containerDiv.offsetHeight; [/code]
When first created, the Canvas will be blank and transparent. You can draw on it using commands such as lineTo, . For example,
[code] var context = myCanvas.getContext("2d"); context.fillRect(0,0, 250, 250); [/code]
Below is an example of Canvas created with this code:
[code] myCanvas=document.createElement('canvas'); myCanvas.style.width = containerDiv.offsetWidth+"px"; myCanvas.style.height = containerDiv.offsetHeight+"px"; // You must set this otherwise the canvas will be streethed to fit the container myCanvas.width=containerDiv.offsetWidth; myCanvas.height=containerDiv.offsetHeight; var context = myCanvas.getContext("2d"); context.fillRect(0,0, 250, 250); [/code]