HTML5 Canvas - Let's Draw!

  • Published on

  • View

  • Download

Embed Size (px)


Let's take a look at the HTML5 element canvas. See how you can draw shapes and images, manipulate single pixels and even animate it. Given as a lecture in the fh ooe in Hagenberg, Austria in December 2011.


<ul><li> HTML5 Canvas </li> <li> The canvas isa 2d bitmap. </li> <li> No layers.No undo.No objects.No moving stuff. </li> <li> </li> <li> </li> <li> How can I create a c anvas? </li> <li> HTMLfallback txtJavaScriptvar canvas = document.getElementsById(a);var ctx = canvas.getContext(2d); </li> <li> I draws quares. </li> <li> con text ctx.fillStyle = blue; he ight ctx.fillRect(0, 0, 150, 50); x y width ctx.strokeStyle = #c66; ctx.lineWidth = 1; ctx.strokeRect(0.5, 60.5, 150, 50); </li> <li> Iwant to d raw an image! </li> <li> create imagevar img = new Image();img.onload = function() { w hen loaded ctx.drawImage(img, 0, 0);}; x yimg.src = nakedrobot.png; image url </li> <li> how can you draw text? </li> <li> css p ropertiesctx.font = bold 40px sans-serif;ctx.fillText(hello kitty, 5, 40); x yhello kitty </li> <li> bring methe pixels! </li> <li> var w = canvas.width;var h = canvas.height; new image arrayvar img = ctx.createImageData(w, h);for (var x = 0; x &lt; w; x++) { for (var y = 0; y &lt; h; y++) { // each pixel has four values var idx = (x + y * w) * 4; // 0 red, 1 green, 2 blue, 3 alpha[idx + 0] = x;[idx + 1] = 255-x;[idx + 2] = 0;[idx + 3] = 255; }} resultctx.putImageData(img, 0, 0); write to canv as </li> <li> </li> <li> close pixealte </li> <li> A nimation function ti ck() { doKeyboard( ); updatePlaye r(); doAI(); draw(); audio(); }var fps = 3 0;setInterval (tick, 1000 /fps) ; </li> <li> get inputdraw updateevery 30ms </li> <li> function tick() { doKeyboard(); updatePlayer(); doAI(); draw(); audio();}var fps = 30;setInterval(tick, 1000/fps); </li> <li> How cani Save anImage? </li> <li> var img = document. getElementsByTagName(img)[0];var canvasImg = canvas.toDataURL("image/png"); returns data:ima ge/png;base64,img.src = canvasImg; iVBORw0KGgoAAAA NS MgAAADICAYAAACt... UhEU canvas image </li> <li> BrowserSupport 67% </li> <li> </li> <li> Summary Canvas is a new 2d bitmap html element. you can draw primitives, imagesand pixels. There are no layers or object. If a pixel gets a new color, theold color is overwritten and lost.A canvas is not sandboxed like flash and can be accessed and drawn onwith javascript. </li> <li> Material Used Banksy Have a Break Banksy Flowing off Banksy Theyre Coming Bansky Tourqay Robot Banksy You have got to be kidding me Banksy follow your Dream Banksy nola Banksy Flower Pollard Street what are you looking at? Banksy Man and Picture of a dog Banksy Anti-Capitalism for sale </li> <li> Material Used 3d teapot model Metal Teapot furry teapot Television Icon Graphics Card Banksy under the Carpet Boxing </li> </ul>