1 / 90

HTML5 Canvas: Powerful Graphics in JavaScript

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.

berthold
Download Presentation

HTML5 Canvas: Powerful Graphics in JavaScript

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. HTML 5 • The <canvas> </canvas>

  2. 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)

  3. 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.

  4. 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.

  5. 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.

  6. 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

  7. What Can The Canvas Be Used for? • Nearly anything that Flash notorious for: • Banner Ads • Animated Landing Pages • Web Games • Video

  8. Video • Video played Directly on Canvas • Can Create frame counter To trigger events

  9. 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)

  10. 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

  11. 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)

  12. 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)

  13. 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>

  14. 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

  15. Canvas Hello World In the <HEAD> of your HTML page, start adding JavaScript <head> <script type="text/javascript"> //Canvas Code Goes Here </script> </head>

  16. 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);

  17. Canvas Hello World After window loads, call start application: Encapsulate Canvas code in it’s own function object: function eventWindowLoaded () { canvasApp(); }

  18. 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

  19. 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() }

  20. 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.

  21. 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);

  22. 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

  23. 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 );

  24. 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

  25. Canvas Hello World Adding An Image: varhelloWorldImage = new Image(); helloWorldImage.onload = function () { context.drawImage(helloWorldImage, 160, 130); } helloWorldImage.src = "helloworld.gif";

  26. Canvas Hello World

  27. Text Mangler

  28. How It Works: Interacting with HTML • Standard HTML <form> elements • JavaScript “change” events to call functions • Draw() function called to re-render

  29. 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()

  30. 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

  31. 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

  32. 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

  33. Simple Animation • The Tile Sheet looks like this

  34. Simple Animation

  35. 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;

  36. 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(); }

  37. 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.

  38. 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);

  39. 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; } }

  40. 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.

  41. 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();

  42. Draw With Paths

  43. 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);

  44. 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

  45. 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.

  46. 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);

  47. 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();

  48. 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.

  49. 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)

  50. 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)

More Related