900 likes | 916 Views
Learn how to utilize the HTML5 Canvas element to create dynamic and interactive graphics using JavaScript. Explore the benefits and capabilities of Canvas for game development, banner ads, web games, video playback, and more.
E N D
HTML 5 • The <canvas> </canvas>
Why Move From Flash to The Canvas? • Easy Tools: a web browser, text editor and JavaScript was all that was required. • The HTML5 Canvas allowed for a bitmapped graphics, much Flash’s bitmapped canvas. • Our specific Type Of Game Development translates well (tile sheets, bitmaps)
What is the HTML5 Canvas? • The HTML5 Canvas is an Immediate Mode bit-mapped area of the screen that can be manipulated with JavaScript and CSS.
What Is Immediate Mode? • Immediate Mode refers to the way the canvas renders pixels on the screen. The HTML5 Canvas completely redraws the bitmapped screen on every frame using Canvas API calls from JavaScript. As a programmer, your job is to set-up the screen display before each frame is rendered.
What Is Retained Mode? • Flash, Silverlight, and DOM <div> manipulation techniques use Retained Mode. In Retained Mode a list of individual display objects is stored and manipulated.
Canvas And The DOM • DOM : Document Object Model • Canvas is a DOM Object • Accessible via the 2D Canvas context • Has both it’s own properties and CSS properties
What Can The Canvas Be Used for? • Nearly anything that Flash notorious for: • Banner Ads • Animated Landing Pages • Web Games • Video
Video • Video played Directly on Canvas • Can Create frame counter To trigger events
What Is It Not Good For? • Some of Flash’s core competencies : • Heavy, time-line based key-frame animation • Vector motion graphics • Secure, monetizable video • Code/asset encapsulation • Advanced Audio applications • Hard Core Games (at the moment)
HTML5 Canvas Properties Canvas Has Three Properties: • width • height • id Width and height read/write which means you can resize the Canvas on the fly
HTML5 Canvas Methods • getContext() : You need the context to draw anything on the Canvas. We will see this shortly • toDataUrl() : Outputs the bitmapped data of the Canvas to a string (can be used to create a screenshot)
HTML5 Canvas And CSS • CSS can be used in conjunction with Canvas object itself. However, individual drawings on the Canvas cannot be manipulated with CSS • Example: you can scale the Canvas using CSS style=”width: 400px; height:400px” • Does not resize but instead scales (like setting width ad height for a Flash embed)
Canvas Hello World In the <body> section of the HTML page, you add a <canvas> tag using code like the following: <canvas id="canvasOne" width="500" height="300"> Your browser does not support the HTML 5 Canvas. </canvas>
Canvas Hello World • Setting up your Canvas app structure is very important to get started. • The next section is code heavy, but we believe it is important to get a code structure down that you can use for your apps • Our structure is not the only way to do it
Canvas Hello World In the <HEAD> of your HTML page, start adding JavaScript <head> <script type="text/javascript"> //Canvas Code Goes Here </script> </head>
Canvas Hello World We need to wait For the Browser Window To Finish Loading so we can be sure all of the JavaScript is available. window.addEventListener("load", eventWindowLoaded, false);
Canvas Hello World After window loads, call start application: Encapsulate Canvas code in it’s own function object: function eventWindowLoaded () { canvasApp(); }
Basic Structure of Canvas Object • Test For Canvas Support • Get a reference to the Canvas object on the HTML page • Get reference to the Canvas 2D context from the Canvas object • Create a stub function used to draw onto the Canvas
Canvas Hello World Basic Structure Of Canvas App function canvasApp () { if (!canvasSupport()) { return; } vartheCanvas = document.getElementById("canvasOne"); var context = theCanvas.getContext("2d"); function draw() { //all the cool drawing stuff goes here } draw() }
Canvas Hello World • Draw filled box as the background • Draw “stroke” box as the border • We need the Canvas context to draw anything • Since we are drawing in immediate mode, we set Canvas context properties one at a time to draw different objects.
Canvas Hello World Background: yellow box, black outline context.fillStyle = "#ffffaa"; context.fillRect(0, 0, 500, 300); context.strokeStyle = "#000000"; context.strokeRect(5, 5, 490, 290);
Canvas Hello World • The background is drawn first. • Since there is no concept of a “display list” in immediate mode, we need to make sure to draw things in the order we want them stacked (i.e. background first, text second) • Advanced: globalCompositeOperation property of the context can be manipulated for layering purposes
Canvas Hello World Adding Text: After drawing the boxes, context.fillStyle is updated with a new color. Think of this like a hand (context) with a crayon. There is only one hand to draw with, so you swap out the crayon (fillStyle) and draw the text. context.fillStyle = "#000000"; context.font = "20px _sans"; context.fillText("Hello world!",195,80 );
Canvas Hello World • Adding an image: • Use JavaScript Image() object to load and reference an image • Use context.drawImage(imageRef, x,y) to draw it on the Canvas
Canvas Hello World Adding An Image: varhelloWorldImage = new Image(); helloWorldImage.onload = function () { context.drawImage(helloWorldImage, 160, 130); } helloWorldImage.src = "helloworld.gif";
How It Works: Interacting with HTML • Standard HTML <form> elements • JavaScript “change” events to call functions • Draw() function called to re-render
Text Mangler • Text : context.font = “64px italic bold _sans” • Resize : (canvas.width, canvas.height) • Scale : style=”width:xxx; height:xxx;” • Alpha : (context.globalAlpha) • Gradient Fills (context.createLinearGradient()) • Shadows : (context.shadowColor ) • Screen Shot: canvas.toDataUrl()
Simple Animation • To animate you need to call a function on an interval to update the Canvas • Drawing objects (circle, boxes), bitmapped images, and video all need to be updated on every frame to animate/play
Simple Animation • Let’s use a tile sheet of a tank and animate it driving across the screen. • This uses a PNG file set as a tile sheet, and interval, and some code change the position of the tank on the Canvas
Simple Animation • Let’s use a tile sheet of a tank and animate it driving across the screen. • This uses a PNG file set as a tile sheet, and interval, and some code change the position of the tank on the Canvas
Simple Animation • The Tile Sheet looks like this
Simple Animation Steps: • First we load in the tile sheet vartileSheet=new Image(); tileSheet.addEventListener('load', eventShipLoaded false); tileSheet.src="tanks_sheet.png"; 2. Next we set up an array of fames from the tile sheet for the tank track varanimationFrames=[1,2,3,4,5,6,7,8]; 3. We create an index to use to specify which frame we are to draw varframeIndex=0;
Simple Animation 4. We set up the rotation, x,y, dx, and dy properties for the tank var rotation=90; var x=50; var y=50; var dx=1; var dy=0; 5. We create a listener function for the tile sheet load function eventShipLoaded() { startUp(); }
Simple Animation 6. The startUp() function will set up an interval to call the draw function every 100 milliseconds function startUp(){ setInterval(drawScreen, 100 ); } 7. The draw() is code heavy. It will re-draw the background, then it will update the x and y coordinates of the tank based on the dx and y values. Next, it will then save the current context, draw the current frame of the tank and restore the current context. Finally, it will update the frameIndex for the tank display. We are rotating the tank 90 degrees, so we will also be adding in a rotation and translation transformation.
Simple Animation function drawScreen() { x=x+dx; y=y+dy; //draw a background so we can wee the Canvas edges context.fillStyle="#aaaaaa"; context.fillRect(0,0,500,500); context.save(); context.setTransform(1,0,0,1,0,0) var angleInRadians =rotation * Math.PI / 180; context.translate(x+16, y+16) context.rotate(angleInRadians);
Simple Animation var sourceX=Math.floor(animationFrames[frameIndex] % 8) *32; var sourceY=Math.floor(animationFrames[frameIndex] / 8) *32; context.drawImage(tileSheet, sourceX, sourceY,32,32,-16,-16,32,32); context.restore(); frameIndex++; if (frameIndex ==animationFrames.length) { frameIndex=0; } }
Draw With Paths • The easiest method to draw on the Canvas is to create a series of paths (like vector drawing) to depict our shapes. • We will use the beginPath(), moveTo(), lineTo(), stroke(), and closePath() methods to create our shapes.
Draw With Paths context.strokeStyle="#ff0000"; context.beginPath(); context.moveTo(100,100); context.lineTo(150,100); context.lineTo(150,150); context.lineTo(100,150); context.lineTo(100,100); context.stroke(); context.closePath();
Rotation Transformation • We can easily rotate the drawn path by applying a simple rotation transformation. • First we reset the Canvas transformation matrix it s “identity” or reset value: context.setTransform(1,0,0,1,0,0); • Next, we set the angle we want the next path to be drawn in with a radian value: context.rotate(45* Math.PI / 180);
A Bit More Advanced • Because the Canvas is an immediate mode drawing surface, some things are vastly more complicated than creating them in something like Flash • Example : Rotating an object on the Canvas
Canvas State • The current contents of the Canvas can be stored in a stack. • Context.save() will save the current state • Context.restore() will restore the previous Canvas state.
Rotation Transformation • We can easily rotate the drawn path by applying a simple rotation transformation. • First we reset the Canvas transformation matrix it s “identity” or reset value: context.setTransform(1,0,0,1,0,0); • Next, we set the angle we want the next path to be drawn in with a radian value: context.rotate(45* Math.PI / 180);
Rotation Transformation context.setTransform(1,0,0,1,0,0); context.rotate(45* Math.PI / 180); context.strokeStyle="#ff0000"; context.beginPath(); context.moveTo(100,100); context.lineTo(150,100); context.lineTo(150,150); context.lineTo(100,150); context.lineTo(100,100); context.stroke(); context.closePath();
Rotation Transformation What happened? The square was rotated, but the top left corner of the Canvas was used at the origin for the rotation. Let’s fix that with a translation transformation.
Rotation Transformation • To rotate an object around its own center point, we must: • Translate the Canvas to the center of our object. • Draw our object 0,0 is it’s current top left corner. • If we want a 50 x 50 square that starts at 100,100, then we must do this translation: context.translate(125,125)
Rotation Transformation • To rotate an object around its own center point, we must: • Translate the Canvas to the center of our object. • Draw our object at 0,0 as is now the current top left corner. • If we want a 50 x 50 square that starts at 100,100, then we must do this translation: context.translate(125,125)