Firstly, you would have this in the html of the page:
The id of the canvas element has been set to "canvas", which is how the javascript can identify the right canvas element to manipulate.<canvas id="canvas" width="400" height="400"> Browser not compatible with HTML5 canvas </canvas>
The width and height of the canvas will be 400px.
And if an incompatible browser is used, it will display the text "Browser not compatible with HTML5 canvas".
And here is an example of the kind of javascript you could use to draw an image (you could have this in script tags or have it in a .js file and call it from src attribute of script tags):
So first it gets the canvas element by using the id we gave it. It then creates the 2D context with that canvas element.var canvas = document.getElementById('canvas'); var context2D = canvas.getContext('2d'); var img = new Image(); img.src = "http://www.blogger.com/img/logo40.png"; context2D.drawImage(img, 100, 50);
It then loads a new image object and then tells it to use the image from http://www.blogger.com/img/logo40.png by assigning it to the src variable of the Image object.
Then it uses the 2D graphics API by calling the drawImg() function.
The first parameter of the function is looking for an image object, the second is the x-position and the third is the y-position.
So here it is (I added style="background-color: #A9A9A9;" to the canvas so you can see it fully):
So there we go, that is an extremely simple use of the canvas. This is just to get you kick-started.
Here's a pastebin of an example full HTML file for this: http://pastebin.com/zrsrdAGP
i should mention, this did not work for me unless I placed the java script under the canvas tag for some reason.
ReplyDeleteI can't get this example to work for me. Canvas displays (w/bg color of course), but no image. :( Inexplicably, the example ON this page displays fine, but if I use the code as supplied OR view page source & use that...nada. Hell, I've even tried a local image. I suppose I'm going elsewhere to learn...maybe I'll come back here once I figure out what's going on.
ReplyDeleteWhat browser are you using?
ReplyDeleteI suggest you get a recent version of Firefox or Google Chrome.