This is a continuation of my journey of learning HTML 5 from the book
The Essential Guide to HTML5: Using Games to learn HTML5 and JavaScript
Now I am on chapter 2, Drawing a Bouncing Ball. I want to write about
drawing an image and moving it across the canvas.
First lets write the necessary variables
var ctx, //save the parameters to variables for easier clearing x=10, y=20, width=50, height=50,
Compared to the previous post, now I save the x, y, width and height
to variables. This will help me upon clearing a specific rectangle area using
clearRect later. As I have mentioned in my previous post.
ctx.clearRect(x,y,width,height);
To draw an image to the canvas is as easy as
img = new Image(); //set an image url img.src = "http://blog.hugeaim.com/wp-content/uploads/2011/07/9099426-symbol-of-the-japanese-earthquake.jpg" ctx.drawImage(img,x,y,width,height);
First we create an image object, give a url to it, then send it to the
drawImage later.
To move it is as easy as,
ctx.clearRect(x,y,width,height); x = x+20; ctx.drawImage(img,x,y,width,height);
To create an illusion of movement, we clear a specific rectangle area where we
previously drew, append 20 pixels to x, then redraw the image.
Then we are done,
Here is the full source code
Drawing and moving an image<script type="text/javascript"> <html> <head> <title>Drawing and moving an image</title> <script> var ctx, //save the parameters to variables for easier clearing x=10, y=20, width=50, height=50, img = new Image(); //set an image url img.src = "http://blog.hugeaim.com/wp-content/uploads/2011/07/9099426-symbol-of-the-japanese-earthquake.jpg" function init() { ctx =document.getElementById("canvas").getContext('2d'); //initial drawing draw(); } function draw(){ ctx.drawImage(img,x,y,width,height); } function move(){ ctx.clearRect(x,y,width,height); x = x+20; draw(); } </script> </head> <body onLoad="init();"> <input type="button" value="Move" onclick="move()"/> <br/> <canvas id="canvas" width="1200" height="1200"> Your browser doesn't support the HTML5 element canvas. </canvas> </body> </html>
View the live code here