480 likes | 725 Views
HTML 5 Tutorial:. Canvas Drawing & Animation. HTML5 Canvas. Most modern browsers support the canvas element and the majority of its features.
E N D
HTML 5 Tutorial: Canvas Drawing & Animation
HTML5 Canvas • Most modern browsers support the canvas element and the majority of its features. • Internet Explorer versions prior to 9 do not support it. You can use ExplorerCanvas to add the same functionality to early versions of Internet Explorer. To use, web developers only need to include a single script tag in their existing web pages.
Canvas • The <canvas> tag is used to display graphics. • The Canvas is a rectangular area whose every pixel can be controlled. • The <canvas> tag is only a container for graphics, you must use a script to actually paint the graphics. • The canvas element has several methods for drawing paths, boxes, circles, characters, and adding images.
Attributes • HTML 5.0 supports the following canvas attributes :
Basic Syntax • Basic Syntax to create canvas : <canvas id="my_canvas" width="800" height="600"> <!-- Insert fallback content here --></canvas> • Once the Canvas is created we can draw various graphics by calling various JavaScript methods on its context. ... <script type="text/javascript"> varc=document.getElementById("my_canvas"); varcontext=c.getContext("2d"); context.fillStyle="#FFAA00"; context.fillRect(0,0,120,80); </script> ...
Basic Syntax • Example : <html> <head> <title>Canvas Demo</title> </head> <body> <canvas id="my_canvas" width="800" height="600"> </canvas> <script type="text/javascript"> var c=document.getElementById("my_canvas"); var context=c.getContext("2d"); context.fillStyle="#FFAA00"; context.fillRect(0,0,120,80); </script> </body> </html>
Using JavaScript • The canvas element has no drawing abilities of its own. All drawing must be done via JavaScript : <script type="text/javascript"> varc=document.getElementById("myCanvas"); varcxt=c.getContext("2d"); cxt.fillStyle="#FF0000"; cxt.fillRect(0,0,150,75); </script> • JavaScript uses the id to find the canvas element : varc=document.getElementById("myCanvas");
Using JavaScript continued… Then, creates a context object : • varcxt=c.getContext("2d"); The getContext("2d") object is a built-in HTML5 object, with many methods to draw paths, boxes, circles, characters, images and more. The next two lines draws a red rectangle: • cxt.fillStyle="#FF0000"; • cxt.fillRect(0,0,150,75); The fillStyle method makes it red, and the fillRect method specifies the shape, position, and size.
Understanding Coordinates • The fillRect method above had the parameters (0,0,150,75). • This means: Draw a 150x75 rectangle on the canvas, starting at the top left corner (0,0). • The canvas X and Y coordinates are used to position drawings on the canvas.
The coordinate system • The 2d rendering context uses a flat Cartesian coordinate system with the origin (0, 0) at the top left. Moving to the right will increase the x value, and moving downwards will increase the y value. Understanding how the coordinate system works is integral if you want to have things draw in the right place. A single unit in the coordinate system is usually equivalent to 1 pixel on the screen, so the position (24, 30) would be 24 pixels right and 30 pixels down. There are some occasions where a unit in the coordinate system might equal 2 pixels, like with high definition displays, but the general rule of thumb is that 1 coordinate unit equals 1 screen pixel. Note: It may not seem obvious, but if you draw something with an origin point beyond the dimensions of the canvas element, it won’t appear on the screen. Only shapes drawn with an origin point, or some part of the shape inside of the canvas element will be visible to you. 2d rendering context Cartesian coordinate system
Example • <!DOCTYPE html><html><head><title>Learning the basics of canvas</title><meta charset="utf-8"><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script><script type="text/javascript">$(document).ready(function() {});</script></head><body><canvas id="myCanvas" width="500" height="500"><!-- Insert fallback content here --></canvas></body></html>
Example • <!DOCTYPE html><html><head>…<script type="text/javascript">$(document).ready(function() {var canvas = $("#myCanvas");var context = canvas.get(0).getContext("2d");});</script></head><body><canvas id="myCanvas" width="500" height="500"><!-- Insert fallback content here --></canvas></body></html> Assign the canvas element to a variable then assign the 2d rendering context to another variable by calling the getContextmethod. Once there is a variable that contains the 2d rendering context we can start drawing.
Example • <!DOCTYPE html><html><head>…<script type="text/javascript">$(document).ready(function() {var canvas = $("#myCanvas");var context = canvas.get(0).getContext("2d"); • context.fillRect(40, 40, 100, 100);});</script></head><body><canvas id="myCanvas" width="500" height="500"><!-- Insert fallback content here --></canvas></body></html> Drawing an object using canvas The square is black because that is the default color of elements drawn with canvas. The method is called fillRect. fillRect draws a rectangle and fills it with a color (in our case black), the strokeRect method draws a rectangle and strokes it - the outline of the rectangle has a line drawn around it.
Example • context.fillRect(40, 40, 100, 100); • context.fillRect(x, y, width, height); fillRect: There are four arguments needed to create a rectangle. The first two are the (x, y) coordinate values for the origin of the square (its top left corner), and the final two are the width and height of the rectangle. The width of a rectangle is drawn to the right of the (x, y) position, and the height of the rectangle is drawn downwards from the (x, y) position. You can see why it’s important to know how the coordinate system works, otherwise you may have assumed the height would draw upwards from the (x, y) position. Drawing an object using canvas Change the width, height and position of the rectangle.
Drawing Paths Aside from rectangles, you can make other shapes by using paths with several canvas functions such as: beginPath() – This function have to be called every time when starts a new path. moveTo() – Set and move your starting point. lineTo() – Draws a straight path from the previous point that defined in the moveTo() or last point that drawn by lineTo(). closePath() – Close path by connecting the last point with the first point. stroke() – Fill the outline of the path. fill() – Fill the path with color. Every shape that you make must consists of at least 3 points as shown below:
Paths - Lines Lines are created a little differently to shapes. They’re actually known as paths. To create a simple path, you have to first call the beginPath method on the 2d rendering context, which effectively says, “get ready, we’re about to start drawing a path.” The next method to call is moveTo, which sets the (x, y) origin of the path we’re about to draw. Following this is a call to lineTo with the (x, y) of the destination of our line, with a call to closePath to finish drawing the path. Finally, a call to stroke will make the line visible by drawing its outline. context.beginPath(); // Start the pathcontext.moveTo(40, 40); // Set the path origincontext.lineTo(340, 40); // Set the path destinationcontext.closePath(); // Close the pathcontext.stroke(); // Outline the path Lines don’t have to be horizontal or vertical, by changing the (x, y) arguments of the lineTo method you can make it diagonal: context.lineTo(340, 340);
Paths - Shapes <script type="text/javascript"> function drawShape() { varmyCanvas = document.getElementById("myCanvas"); varctx = myCanvas.getContext("2d"); ctx.beginPath(); ctx.moveTo(75,0); ctx.lineTo(150,100); ctx.lineTo(0,100); ctx.closePath(); ctx.fill(); } </script> … <body onLoad="drawShape()"> <canvas id="myCanvas" width="300" height="300"> <!-- Insert fallback content here --> Sorry, your browser doesn't support canvas technology </canvas> </body>
Paths - Shapes Let’s create some others shape such as diamond with path. In order to create a diamond shape from triangle, you have to add a new point at the bottom that can connect with the second and the third points. In this case , the first point is located at (75,0), second point is located at (150, 100) and the third point is located at (0,100) as shown below: So our new point must have a same x-axis (75) value with the first point but different y-axis (200) value from others. Try to insert the following code before your last current lineTo function, to create a new bottom point: ctx.lineTo(75, 200); Save your code and run it, you should see a diamond shape appeared, instead of a triangle. Cool right? You can use the same concept to draw any other complicated shape that you want, but for drawing arc or circles we use ‘arc‘ function.
Circles A circle is a fairly complex shape, and because of this there isn’t actually a special method in canvas to create a circle. What there isis a method for drawing arcs, which is all a circle really is—an arc joined at both ends. context.arc(230, 90, 50, 0, Math.PI*2, false); context.arc(x, y, radius, startAngle, endAngle, anticlockwise); There are six arguments used in the creation of an arc; the (x, y) coordinate values for the origin of the arc (the centre of the circle in our case), the radius of the arc, the start angle, the end angle, and finally a boolean value that draws the arc anti-clockwise if true, or clockwise if false. It is important to properly understand how the start angle and end angle arguments work. In short, an arc in canvas is defined as a curved path that starts at a distance from the (x, y) origin equal to the radius, and is at the angle defined by the start angle. The path ends at the end angle one radius away from the (x, y) origin. context.beginPath(); // Start the pathcontext.arc(230, 90, 50, 0, Math.PI*2, false); // Draw a circlecontext.closePath(); // Close the pathcontext.fill(); // Fill the path Lines don’t have to be horizontal or vertical, by changing the (x, y) arguments of the lineTo method you can make it diagonal: context.lineTo(340, 340);
Circles It’s important to note that angles in canvas are in radians and not degrees and, without going into too much detail, it’s safe to assume that 360 degrees (a complete circle) is 2π (pi multiplied by 2) radians. var degrees = 1; // 1 degreevar radians = degrees * (Math.PI / 180); // 0.0175 radiansto make things easier you can use the image as a quick guide for the angle along a circle in radians. Converting between degrees and radians There is a formula for more complicated conversions.
Circles context.arc(230, 90, 50, 0, Math.PI*2, false); context.arc(x, y, radius, startAngle, endAngle, anticlockwise); The circle example: the start angle is 0, the beginning of the arc, and the end angle is Math.PI*2 (pi multiplied by 2); these angles are the start and end of a circle. what would the end angle be if you wanted to draw half a circle instead? context.arc(230, 90, 50, 0, Math.PI, false); // Draw a semi-circle context.beginPath(); // Start the pathcontext.arc(230, 90, 50, 0, Math.PI*2, false); // Draw a circlecontext.closePath(); // Close the pathcontext.fill(); // Fill the path
Circles To draw a simple circle, we use the canvas arc method with a 2 * PI length. <script>function circle(){var canvas = document.getElementById("canvas1"); var context = canvas.getContext("2d");context.beginPath();context.lineWidth="2";context.arc(100, 100, 90, 0, 2 * Math.PI);context.stroke();}circle(); </script> • The canvas has a size of 200 x 200 pixels. The center of the circle is at x = 100, y = 100, given by x and y arguments of the function arc. • The radius of 90 pixels is the third argument. The third and fourth arguments give the starting angle, 0 and the final angle, twice PI. • We can ignore the argument about the direction of rotation.
Styles – Change Colourand Line Width Cutomizing shapes using: fillStyle- Fill shape with rgbcolours lineWidth- Set width of outline of the shape strokeStyle- Fill shape outline with rgbcolour Fill a shape with green, 1px width of outline and fill the outline with blue. ctx.fillStyle = "rgb(102, 204, 0)"; //filled green for inner content ctx.lineWidth = 1; // 1px width of outline ctx.strokeStyle = "rgb(0, 50, 200)"; //filled red for outline ctx.closePath(); //Fill the shape with colors that defined above ctx.fill(); ctx.stroke(); Note: You must call ‘closePath‘ function before you fill the shape with any colors, else your shape will has missing outline for the last point as shown below:
Styles - colour Change the colourof our shapes and lines. context.fillStyle = "rgb(255, 0, 0)";context.fillRect(40, 40, 100, 100); Setting the fillStyle property of the 2d rendering context changes the colourthat shapes and paths are filled in as. You can use: • an rgb (red, green, and blue) color value • any valid CSS color value, like a hex code (eg. #FF0000 or the word “red”). In the example, the colouris set to red (full red, no green, no blue) and your square should look something like this: *Note: setting the fillStyle property means that everything you draw after setting it will be in that colour. It important to be aware of this in case you only wanted to change the colourof one object.
Styles - colour Setting the fillStyle property means that everything you draw after setting it will be in that colour. One way to get around this is to set the fillStyle property back to black (or another colour) once you’ve drawn your objects to canvas, like so: context.fillStyle = "rgb(255, 0, 0)"; context.fillRect(40, 40, 100, 100); // Red square context.fillRect(180, 40, 100, 100); // Red square context.fillStyle = "rgb(0, 0, 0)"; context.fillRect(320, 40, 100, 100); // Black square You can also do the same thing with stroked shapes and paths by using the strokeStyle property. For example, the following is the same as previous example except it’s using stroked outlines instead of fills: context.strokeStyle= "rgb(255, 0, 0)"; context.strokeRect(40, 40, 100, 100); // Red square context.strokeRect(180, 40, 100, 100); // Red square context.strokeStyle = "rgb(0, 0, 0)"; context.strokeRect(320, 40, 100, 100); // Black square
Styles - colour There’s nothing stopping you from combining both fillStyle and strokeStyle to give a shape a fill and stroke that are completely different colours. context.strokeStyle = "rgb(255, 0, 0)";context.beginPath();context.moveTo(40, 180);context.lineTo(420, 180); // Red linecontext.closePath();context.stroke();context.strokeStyle = "rgb(0, 0, 0)";context.beginPath();context.moveTo(40, 220);context.lineTo(420, 220); // Black linecontext.closePath();context.stroke();
Styles – line width Changing line width The lineWidth property of the 2d rendering context. By default the lineWidth property is set to 1, but you can set it to anything you want. context.lineWidth = 5; // Make lines thickcontext.strokeStyle = "rgb(255, 0, 0)";context.beginPath();context.moveTo(40, 180);context.lineTo(420, 180); // Red linecontext.closePath();context.stroke();context.lineWidth = 20; // Make lines even thickercontext.strokeStyle = "rgb(0, 0, 0)";context.beginPath();context.moveTo(40, 220);context.lineTo(420, 220); // Black linecontext.closePath();context.stroke(); Make a slightly thicker red line and an overly thick black line lineWidthworks just as well on shapes: context.lineWidth = 5; // Make lines thickcontext.strokeStyle = "rgb(255, 0, 0)";context.strokeRect(40, 40, 100, 100); // Red squarecontext.strokeRect(180, 40, 100, 100); // Red squarecontext.lineWidth = 20; // Make lines even thickercontext.strokeStyle = "rgb(0, 0, 0)";context.strokeRect(320, 40, 100, 100); // Black square Makes two slightly thicker red squares with an overly thick black square.
Drawing Text Canvas is not just for graphics and images, you can also use it to display text. (You will probably not use cavas to draw text but instead use regular HTML) Text in canvas is drawn as an image, which means that it is not selectable with a mouse cursor like normal text in a HTML document. Once text has been drawn it can’t be edited unless you erase it and redraw it again. **The benefit to drawing text in canvas is that you can use all the transformations and other functionality that comes with drawing in canvas. var text = "Hello, World!";context.fillText(text, 40, 40); The fillText method of the 2d rendering context takes four arguments (one is optional, so we’ve left it out for now); the first is the string of text you want to draw, and the second and third are the (x, y) coordinate values for the origin of the text (the bottom left). The font property takes a string value in exactly the same way as the font property in CSS. The default font settings for text in canvas are 10px sans-serif. To set the font property of the 2d rendering context var text = "Hello, World!"; context.font = "30px serif"; // Change the size and font context.fillText(text, 40, 40);
Drawing Text make the text italic var text = "Hello, World!"; context.font = "italic 30px serif"; context.fillText(text, 40, 40); the word italic has been added to the font string. There are many more settings you can use for the font. Create stroked text: var text = "Hello, World!"; context.font = "italic 60px serif"; context.strokeText(text, 40, 100); the strokeText method, which takes exactly the same parameters as fillText.
Erasing the CanvasclearRect() Canvas has two options for erasure at your disposal: the clearRect method, or the width/height method. The clearRect method of the 2d rendering context Say you’ve just drawn a square and a circle on to the canvas: context.fillRect(40, 40, 100, 100);context.beginPath();context.arc(230, 90, 50, 0, Math.PI*2, false);context.closePath();context.fill(); And you’ve now decided, to wipe the canvas clean. To do this, call clearRect with the (x, y) origin of the canvas, its width, and its height. If the canvas was 500 pixels wide and 500 pixels tall then the call to clearRect would look like this: context.clearRect(0, 0, 500, 500); You can also even call clearRect when you don’t know the size of the canvas by using the jQuery width and height methods, like so: context.clearRect(0, 0, canvas.width(), canvas.height()); Which would look like this in its entirety: var canvas = $("#myCanvas");var context = canvas.get(0).getContext("2d");context.fillRect(40, 40, 100, 100);context.beginPath();context.arc(230, 90, 50, 0, Math.PI*2, false);context.closePath();context.fill();context.clearRect(0, 0, canvas.width(), canvas.height());
Erasing the Canvas clearRect() You don’t have to clear the entire canvas . You can just as easily clear a particular area of it. The arguments in clearRect can be changed so a very specific area is cleared For example, if we wanted to remove only the square in the example then you would call clearRect like so: context.clearRect(40, 40, 100, 100); • Which leaves you with a circle. You could quite easily remove the circle instead by changing the arguments of clearRect to the following: context.clearRect(180, 40, 100, 100); • should leave just a square Remember that the origin of an arc is its centre, so to get the correct origin for the clearRect method we need to take the origin of the arc and subtract its radius for both the x and y. context.fillRect(40, 40, 100, 100);context.beginPath();context.arc(230, 90, 50, 0, Math.PI*2, false);context.closePath();context.fill();context.clearRect(230, 90, 50, 50); This example should take a big slice out of your circle: This technique is sometimes used to draw complex shapes quickly and easily by drawing a basic shape and chopping bits off of it.
Erasing the Canvas width/height Canvas has two options for erasure at your disposal: the clearRect method, or the width/height method. The width/height method: If you only want to erase everything on the canvas and start again from scratch then you might want to consider the width/height method to reset a canvas back to its default, fresh state. The idea is that when the width and height attributes of a canvas element are set, at any point, the canvas should be cleared back to its original state. This method does have some drawbacks: absolutely everything in the canvas is reset, including styles and colors. This is why you should only use this method if you’re prepared to completely reset the canvas, not just wipe the display clean. context.fillStyle = "rgb(255, 0, 0)";context.fillRect(40, 40, 100, 100);context.beginPath();context.arc(230, 90, 50, 0, Math.PI*2, false);context.closePath();context.fill(); This will draw a red square and circle onto the canvas, nothing crazy yet. Add in the canvas reset: canvas.attr("width", canvas.width()); canvas.attr("height", canvas.height()); jQueryattr method is used to get/set the width and height attributes of the canvas element. You are passing the name of the attribute you want to edit (width and height) followed by the value you want to set it to (the same width and height as it was previously). If all went well you should see a blank canvas.
Erasing the Canvas width/height context.fillStyle = "rgb(255, 0, 0)";context.fillRect(40, 40, 100, 100);context.beginPath();context.arc(230, 90, 50, 0, Math.PI*2, false);context.closePath();context.fill(); canvas.attr("width", canvas.width()); canvas.attr("height", canvas.height()); Now add the following line after clearing the canvas with the width/height method: context.fillRect(40, 40, 100, 100); You may be expecting to draw a red square. (Remember: we set the fillStyle property previously.) So why on earth is it drawing a black square? Absolutely everything in the canvas is reset, including styles and colors, when using width/height method.
Fullsize Canvas The easiest way to do it is to set the width and height of the canvas element precisely to the pixel width and height of the browser window. We can get access to the width and height of the window by using the window browser object and a bit of jQuery magic: varcanvas = $("#myCanvas"); var context = canvas.get(0).getContext("2d"); canvas.attr("width", $(window).get(0).innerWidth); canvas.attr("height", $(window).get(0).innerHeight); context.fillRect(0, 0, canvas.width(), canvas.height()); Use $(window).get(0).innerHeight instead of $(window).height() is because the latter doesn’t seem to return the full height in all browsers. You’ll notice that this method hasn’t actually worked properly as there is still a white gap around the canvas element and scrollbars in the browser window: To fix this we need to use some CSS, so open up a new file in your favourite text editor and save it as canvas.css in the same directory as your HTML document. Put this inside of the CSS file and save it: * { margin: 0; padding: 0; } html, body { height: 100%; width: 100%; } canvas { display: block; }
Fullsize Canvas * { margin: 0; padding: 0; } html, body { height: 100%; width: 100%; } canvas { display: block; } The first line resets the margin and padding of every HTML element to 0, removing the white border you can see in the screenshot above. The second line isn’t entirely necessary, but makes sure that the html and body elements are the full width and height of the browser window. The final line changes the canvas element from inline to block, which allows the width the height to be set properly, in turn allowing it to take the full width and height of the browser window without causing scrollbars. **Note: This is commonly known as a CSS reset; there are much better ways of doing it. To use this CSS in the HTML document you need to add the following line before the jQueryscript element, inside of the head element: <linkhref="canvas.css" rel="stylesheet" type="text/css"> Unfortunately we’re not done yet. If you resize the browser window the canvas element will stay at the size it was before, causing scrollbars if you shrink it too much:
Fullsize Canvas To solve the resize problem, you need to resize the canvas element at the same moment that the browser window is resized. Use the jqueryresizemethod, which is fired at the moment a browser window is resized. $(window).resize(resizeCanvas); function resizeCanvas() { canvas.attr("width", $(window).get(0).innerWidth); canvas.attr("height", $(window).get(0).innerHeight); context.fillRect(0, 0, canvas.width(), canvas.height()); }; resizeCanvas(); the jQueryresize method has been set to call the resizeCanvas function when the browser window is resized All the functionality you had previously to set the width and height of the canvas element has been moved into that function, including the drawing of the rectangle the size of the canvas (remember: changing the width and height will reset the canvas, so everything has to be redrawn). The final addition is a call to the resizeCanvas function to kick things off when the page is loaded for the first time. If you try that now you’ll notice the canvas element resizes and no scrollbars appear.
Canvas Animation HTML5 canvas provides methods to draw an image and erase it completely. We use Javascript to simulate good animation on a HTML5 canvas. Good Javascript animation needs to loop, updating the coordinates of every object on the canvas/stage; and it should be fast enough to be perceived as a fluid movement. Following are the three Javascript methods which can be used to animate an object/image on a canvas: * requestAnimationFrame() is not supported in older browsers.
Canvas Animation the making of bouncing ball animation with purely HTML5 and JavaScript
Canvas Animation We are going to draw a circle on the canvas element by using JavaScript, so let’s start to define all the variables that we are going to use as shown below: <script type="text/javascript"> varcanvas; varctx; varx = 568; vary = 262; varmx = 2; varmy = 4; varWIDTH = 568; varHEIGHT = 262; </script> Description of variables canvas – This variable will be use as a reference to the canvas object ctx– A variable to hold the value of the context x– A x-axis value (the value must be same with the canvas’s width) y– A y-axis value (the value must be same with the canvas’s height) mx– A prefix x-axis value for animation my– A prefix y-axis value for animation WIDTH– Width of the canvas HEIGHT– Height of the canvas Note: Place your JavaScript after the <canvas>, but before the </body> tag.
Canvas Animation create a function called ‘init()’, which is the function that we call to start everything. <script type="text/javascript"> function init() { canvas = document.getElementById("myCanvas"); ctx= canvas.getContext("2d"); return setInterval(draw, 20); } init(); </script> First, initialize the ‘init()’ function and get access to the canvas object with the ID and define the context as 2d, which allow us to use the JavaScript Canvas function later. The next line use ‘setInterval(function, time)’ to call the ‘draw’ function every 20 milliseconds. Next, create a function called ‘draw’ and insert it after the ‘init’ function that we declared just now. This function draw the circle and animate the circle for us. function draw() { circle(x, y, 20); } First of all, we create a circle by calling a ‘circle()’ function, and passing the parameters of x, y and the radius(size) to it, which we will define later as shown below: function circle(x,y,r) { ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI*2, true); ctx.fill(); }
Canvas Animation To create a perfect circle, we have to begin drawing with ‘beginPath’ function, follow with ‘arc’ and ‘fill’ function. beginPath() – allow us to start a new path arc() – to define the size and shape of circle fill() – Fill the circle with color (default color is black) Our circle has been defined by ‘circle(x, y, 20);’, which means that, the circle has a radius of 10 and its origin is at (x,y). To move the circle, we need to pass in the value to the (x,y) parameters as shown below: function draw() { circle(x, y, 20); if (x + mx > WIDTH || x + mx < 0) mx = -mx; if (y + my > HEIGHT || y + my < 0) my = -my; x += mx; y += my; } The variables mx (with prefix value 2) and my (with prefix value 4) determine the changes of x and y on every 20 milliseconds). To make sure the circle stays within the canvas, check its x and y value, to make sure not greater or less than the canvas size. Save your document and run it on browser, you should see something similar as below:
Canvas Animation Why is it an animated line? You need to clear the stage bewtween drawings to give the illusion of movement. Create a ‘clear()’ function. We use the ‘clear()’ function to erase everything on the canvas for us, it will erase every single previous circle. function clear() { ctx.clearRect(0, 0, WIDTH, HEIGHT); } //init the clear inside the draw() function function draw() { clear(); } Save your document again, run it and you should get a prefect bouncing circle
Canvas Animation <!DOCTYPE HTML> <head></head> <body> <canvas id="canvas" height="300px" width="400px" style="border:1px solid #000"></canvas> <script> player = new Object(); player.x = 5; player.y = 5; canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); setInterval(draw,100); function draw(){ canvas.width = canvas.width; ctx.beginPath(); ctx.fillRect(player.x,player.y,30,30); ctx.closePath(); player.x++; } </script> </body> </html> The first line in the draw() function is using the width/height method of erasing the canvas element. The player.x value gets an increment of 1.
Readings • Part 1 – Introduction • Part 2 – Basic Shapes • Part 3 – Paths and Text • Part 4 – Transformations • Part 5 – Basic Animation • Part 6 – Managing Animated Shapes
References • Learning the basics of HTML 5 by Rob Hawkes. Retrieved from http://www.netmagazine.com/tutorials/learning-basics-html5-canvas[Chapter 3 of Foundation HTML5 Canvas: For Games and Entertainment by Rob Hawkes.] • HTML5 Canvas For Absolute Beginners – Part 1 • http://developer.practicalecommerce.com/articles/2908-Drawing-Basic-Shapes-with-HTML5-Canvas • http://www.techrepublic.com/blog/webmaster/html5-working-with-the-canvas-element/565?tag=content;blog-list-river • http://webdesign.about.com/od/examples/l/z-draw-canvas-examples.htm • http://www.scriptol.com/html5/canvas/circle.php • http://developer.apple.com/library/safari/#documentation/AudioVideo/Conceptual/HTML-canvas-guide/AnimatingtheCanvas/AnimatingtheCanvas.html • http://ie.microsoft.com/testdrive/Graphics/RequestAnimationFrame/Default.html