Hello,
HTML5 canvas is such a good subject to write on and to learn. Eveyday you learn something new. Today we will find out how we can draw an image on our canvas. We can use this feature to set a background image to our drawing if we like.
Here is our final result as shown below
Now lets check how to do it.
Canvas Markup
1 2 3 |
<canvas id="mycanvas" width="700" height="700"> Your browser does not support HTML5 Canvas. Try downloading latest Chrome, Firefox, Safari, Opera or Internet explorer. </canvas> |
The Javascript
Now lets look at our Javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
function canvasImgExperiment() { var mycanvas = document.getElementById("mycanvas"); var cnvcontext = null; var x,y = 0; if(mycanvas && mycanvas.getContext) { cnvcontext = mycanvas.getContext("2d"); // background cnvcontext.fillStyle = "#FFFFFF"; cnvcontext.fillRect(0,0,500,500); } else { return false; } // drawing an image on our canvas // a 673pxx673 example image var img = new Image(); img.onload = function() { cnvcontext.drawImage(img,20,20); // lets draw some text cnvcontext.fillStyle = "#C00000"; cnvcontext.font = "40px arial"; cnvcontext.fillText("Hello Jas",250,300); } img.src = "jas.png"; // savings our canvas as an image } canvasImgExperiment(); |
As you can see that its that simple.
Few key points that you should keep in mind
- context.drawImage(imageElement,x,y) is the function we will use to draw actual image.
- It is important that image is loaded to be able to be drawn. That is why we used img.onload event.
- Path to image can be local, from internet, absolute or relative.
Anything that you draw after drawing the image will appear above the image. Like that way we wrote “hello jas” text.
In the next post I will show you how to save our canvas drawing to a file.
I hope that you found this post useful. Just in case I got any fact wrong please let me know. Learning together is something that is always helpful.
Cheers
Leave a Reply