RC151 010d Html5 Canvas

download RC151 010d Html5 Canvas

of 7

Transcript of RC151 010d Html5 Canvas

  • 8/3/2019 RC151 010d Html5 Canvas

    1/7

    1 Getting Started withJPA 2.0

    http://beautyoftheweb.com/http://beautyoftheweb.com/http://beautyoftheweb.com/http://beautyoftheweb.com/
  • 8/3/2019 RC151 010d Html5 Canvas

    2/7

    DZone, Inc. | www.dzone.com

    GetMoreRefcardz!Visitrefcardz.com

    51

    H

    TML5Canvas

    By Simon Sa

    INTRODUCTION TO CANVAS

    The HTML element allows or on-the-y creation o graphs,diagrams, games, and other visual elements and interactive media. It alsoallows or the rendering o 2D and 3D shapes and images, typically viaJavaScript.

    var can = document.getElementById(canvas1);var ctx = can.getContext(2d);

    ctx.llText(Hello World!, 50, 50);

    Canvas is perhaps the most visible part o the new HTML5 eature set,with new demos, projects, and proos o concept appearing daily.

    Canvas is a very low-level drawing surace with commands or makinglines, curves, rectangles, gradients and clipping regions built in. There isvery little else in the way o graphics drawing, which allows programmersto create their own methods or several basic drawing unctions suchas blurring, tweening, and animation. Even drawing a dotted line issomething that must be done by the programmer rom scratch.

    Canvas is an immediate drawing surace and has no scene graph. Thismeans that once an image or shape is drawn to it, neither the Canvas norits drawing context have any knowledge o what was just drawn.

    For instance, to draw a l ine and have it move around, you need to do

    much more than simply change the points o the line. You must clearthe Canvas (or part o it) and redraw the line with the new points. Thiscontrasts greatly with SVG, where you would simply give the line a newposition and be done with it.

    HotTip

    You can visit the evolving specifcation or Canvas at the WHATWG site:

    http://www.whatwg.org/specs/web-apps/current-work/multipage/

    the-canvas-element.html.

    Browser Support and Hardware AccelerationCanvas is supported by Fireox 1.5 and later; Opera 9 and later; andnewer versions o Saari, Chrome, and Internet Explorer 9 and 10.

    The latest versions o these browsers support nearly all abilities o the

    Canvas element. A notable exception is drawFocusRing, which nobrowser supports eects.

    Hardware acceleration is supported in some variation by all currentbrowsers, though the perormance gains dier. It is difcult to benchmarkbetween the modern browsers because they are changing requently, butso ar IE9 seems to consistently get the most out o having a good GPU.On a machine with a good video card it is almost always the astest atrendering massive amounts o images or canvas-to-canvas draws.

    Accelerated IE9 also renders fllRect more than twice as ast as the othermajor browsers, allowing or impressive 2D particle eects [1]. Chromeoten has the astest path rendering but can be inconsistent betweenreleases. All browsers render images and rects much aster than paths ortext, so it is best to use images and rects i you can regardless o whichbrowsers you are targeting.

    Canvas SVG

    Support All modern versions of Chrome,

    Saari, Fireox, and Opera have at

    least some support. Internet Explorer

    9+ has support. Almost all modern

    smart phones.

    Internet Explorer 7 and 8 have

    limited support through the excanvas

    library.

    Rapidly growing in popularity

    SVG support in all modern brows-

    ers. Almost all modern smart phones

    Stateul-ness

    Bitmapped, immediate drawing

    surace

    Shapes are drawn and nothing is

    remembered about their state.

    Vector-based, retained drawing

    surace

    Every drawn shape is a DOM object

    OtherConsider-ations

    Generally faster

    All event handling and statefulness

    must be programmed yoursel.

    Canvas will be effectively disabled

    (rendering nothing) i scripting is

    disabled.

    Generally slower, especially past

    10,000 objects.

    Since all SVG elements are DOM

    objects, stateulness is built in and

    event handling is much easier.

    Easier for a designer to work with,

    many programs such as Illustrator can

    output SVG

    SVG has built-in support for

    animation.

    Accessi-bility

    Difcult to interface with other

    DOM objects

    Working with text can be difcult.

    Recreating text-based DOM ele-

    ment unctionality is strongly advised

    against, even in the specifcation

    itsel.

    Cannot operate when scripting is

    disabled.

    All SVG objects are already DOM

    objects.

    Text is searchable by the browser

    and web crawlers.

    brought to you by...

    CONTENTS INCLUDE:

    n Introduction to Canvasn Browser Support and Hardware Accelerationn What Canvas Can and Cannot Don A Comparison with SVGn Canvas Perormancen Creating a Canvas and More!

    HTML 5 CanvaA Web Standard for Dynamic Graphi

    http://buildmypinnedsite.com/
  • 8/3/2019 RC151 010d Html5 Canvas

    3/7

    2 HTML5 Canvas

    DZone, Inc. | www.dzone.com

    Best suitedor

    Games, fast graphics

    Very large amounts of objects

    Creating high-performance content

    Accessibility oriented content or

    text-oriented content

    Easily scalable shapes

    Charts, graphs, and other mostly

    static data displays

    Creating interactive content quickly.

    What Canvas Can and Cannot DoThe specifcation advises against using Canvas to render static content.

    There are many reasons to not use Canvas i typical image and textelements will sufce. I scripting is disabled on the client, the Canvaswill be useless. Text drawn on Canvas is not selectable, searchable, orcrawlable by web spiders. For the same reason, Canvas makes webaccessibility more difcult. I you are looking to simply stylize text or roundo the edges o a text area, you should see i the desired eects (such asshadows or rounded corners) are possible with CSS3 beore opting to usea Canvas.

    As o August 2011, Canvas does not look the same on all browsers. Theimplementations o anti-aliasing (or not) dier, and other quirks can causegradients, text, and scaled objects to look dissimilar. For instance, until aew months ago, Chromes handling o gradients would disregard opacityand take the last-known non-gradient colors opacity instead! Both thespecifcation and implementations o Canvas should be consideredslightly, yet constantly, evolving.

    A Comparison with SVGCanvas is a very exible drawing surace but may not be appropriateor all projects. Most immediately relevant when planning a web-app isbrowser support. Internet Explorer 7 and 8 only support Canvas throughthe excanvas library. Excanvas perormance degrades very quickly withanimation, so any animated web-apps that must target Internet Explorer 7and 8 should not use canvas. Note that excanvas is also no longer underactive development.

    The other large dierence is the stateulness o each. Canvas is animmediate drawing surace whereas SVG is retained, meaning that theDOM remembers every drawn SVG element and each element has aully-defned DOM object associated with it, event handlers included.This makes implementing interactivity with SVG much easier than Canvas,but it also introduces a large amount o overhead that is unsuitable orperormance-needing applications.

    The bottom line is that SVG is easier to program or rom the get-go, butCanvas is more powerul. The decision to use either should rest upon whatplatorms you are targeting, how much perormance will be needed, whatlibraries you wish to use, and ease o development based on your (teams)current knowledge and skillset.

    For an in-depth comparison, see the IE teams blog post: http://blogs.msdn.com/b/ie/archive/2011/04/22/thoughts-on-when-to-use-canvas-and-svg.aspx

    Canvas PerformanceWhile the low-level of Canvas might make development slower, itoutshines the other options when perormance is crucial, especially whenthere are tens of thousands of objects to load and draw. While havingeach SVG object be a DOM object makes events and object modifcation

    easier to code, the overhead involved makes SVG unsuitable or complex,interactive apps. Creating 10,000 shapes in Canvas is a very ast process,while creating the same shapes in SVG means creating tens o thousandso SVG DOM nodes, resulting in a much slower process.

    Canvas can be very ast, but it is up to the programmer to keep it that way.Many o the optimizations that might be taken care o by more advanceddrawing rameworks must be done by the programmer. Speed becomesimportant, and any serious Canvas developer should amiliarize himselwith the typical concepts o graphics perormance, such as invalidationsand viewports.

    Additionally, dierent drawing operations are aster or slower than others,and dierent methods o accomplishing the same task can take wildlydierent times. I will go over a ew o them in the fnal section.

    CREATING A CANVAS

    The tag syntax or a Canvas is as ollows:

    This text is displayed if you do not have a canvas-capable browser.

    Note how width and height are attributes just like id. The CSSwidth and height are distinct and are not used or sizing the Canvas.

    Canvas Attributes

    Name/Method Description

    width Deault 300. Also a tag attribute, sets the width o the Canvas

    in pixels.

    height Deault 150. Also a tag attribute, sets the height o the Canvas

    in pixels.

    toDataURL( [type, ...]) Returns a data:URL or the image in the Canvas.

    The frst optional argument controls the type o the image to

    be returned (e.g., PNG or JPEG). The default is image/png; that

    type is also used i the given type isnt supported. The otherarguments are specifc to the type, and control the way that the

    image is generated, as given in the table below.

    toBlob(callback [, type, ... ]) Creates a Blob object representing a le containing the image in

    the Canvas and invokes a callback with a handle to that object.

    The second optional argument controls the type o the image

    to be returned (e.g., PNG or JPEG). The default is image/png;

    that type is also used i the given type isnt supported. The other

    arguments are specifc to the type, and control the way that the

    image is generated, as given in the table below.

    This is an extremely new (May 2011) method or getting the

    contents of a Canvas. Note that it is also asynchronous.

    getContext(in DOMString

    contextID, in any... args)

    Returns an object that exposes an API or drawing on the Can-

    vas. The frst argument specifes the desired API. Subsequent

    arguments are handled by that API.

    Returns null i the given context ID is not supported or i the

    Canvas has already been initialized with some other (incompat-

    ible) context type (e.g. trying to get a 2d context after getting

    a webgl context).

    It is important to note that unlike many HTML Elements, width and heightare attributes o the Canvas element itsel and not style attributes. Settingthe style width and height o the Canvas will scale the Canvas instead.

    State and Transformations

    Method Description

    save() Pushes the current context state onto the stack.

    restore() Pops the top state on the stack, restoring the context to that state.

    sca le (x, y ) Appl ies a scaling t ranso rmation to the cur rent t ranso rmationmatrix

    rotate(angle) Applies a rotation transormation to the current transormationmatrix. The angle is in radians.

    transorm(m0, m1, m2,m3, m4, m5)

    Applies the supplied transormation matrix to the currenttransormation matrix.

    setTransorm(m0, m1,m2, m3, m4, m5)

    Replaces the current transormation matrix with the giventransormation matrix.

    The transormation matrix is an important part o drawing complex shapeson Canvas, though complete understanding o how one works is notimmediately necessary. Using the rotate, scale, and translate methods willmodiy the matrix. It can be modifed directly (but never retrieved) withtransorm and setTransorm.

    http://blogs.msdn.com/b/ie/archive/2011/04/22/thoughts-on-when-to-use-canvas-and-svg.aspxhttp://blogs.msdn.com/b/ie/archive/2011/04/22/thoughts-on-when-to-use-canvas-and-svg.aspxhttp://blogs.msdn.com/b/ie/archive/2011/04/22/thoughts-on-when-to-use-canvas-and-svg.aspxhttp://blogs.msdn.com/b/ie/archive/2011/04/22/thoughts-on-when-to-use-canvas-and-svg.aspxhttp://blogs.msdn.com/b/ie/archive/2011/04/22/thoughts-on-when-to-use-canvas-and-svg.aspx
  • 8/3/2019 RC151 010d Html5 Canvas

    4/7

    3 HTML5 Canvas

    DZone, Inc. | www.dzone.com

    To not interere with objects drawn ater such transormations, save andrestore are typically called beore and ater each transormed element isdrawn to the Canvas.

    While Canvas does not remember shapes and images drawn, it does keeptrack o several drawing rules that comprise its state. The methods saveand restore will push or pop the state onto or o o a stack, saving andrestoring not only the transormation matrix, but also the current clippingregion, as well as all o the stateul attributes:

    strokeStyle lineWidth miterLimit

    llStyle lineCap shadowOffsetX

    globalAlpha lineJoin shadowOffsetY

    shadowBlur shadowColor globalCompositeOperation

    font textAlign textBaseline

    Compositing

    Property Description

    globalAlpha Gets or sets the alpha value applied to all drawing operations.

    Deault is 1.0

    globalCompositeOp-

    eration

    Gets or sets the current composite operation. Deault is "source-

    over".

    All drawing operations are aected by the two compositing attributes. Inthe ollowing images, a blue square is drawn to represent shapes alreadyexisting on a canvas, then the globalCompositeOperation is set to thespecifed value and a red circle is drawn.

    In the following, existing content is dened as any pixels that werealready drawn and not previously transparent.

    globalCompositeOperation

    Result Description

    source-over

    The default. New content is drawn over existing content.

    source-in

    New content is only drawn where existing content was non-transparent.

    source-out

    New content is drawn only where there was transparency.

    source-atop

    New content is drawn only where its overlap existing content.

    destination-over

    Opposite o source-over. It acts as i new content is drawnbehind existing content.

    destination-in

    Opposite o source-in. Existing content is drawn only wherenew content is non-transparent.

    destination-out

    Opposite o source-out. Existing content is drawn only wherenew content is transparent. Acts as i existing content is drawneverywhere except the where the new content is.

    destination-atop

    Opposite of source-atop. New content is drawn, and then oldcontent is drawn only where it overlaps with new content.

    lighter

    Where new content overlaps old content, color is determinedby adding the color values.

    copy

    New content replaces all old content.

    xor

    New content is drawn where old content is transparent. Wherethe content o both old and new are not transparent, transpar-ency is drawn instead.

    Colors and Styles

    Method/Property Description

    strokeStyle Gets or sets the current style used or stroking shapes. Can be

    a string, CanvasGradient or CanvasPattern. The string must be

    parsed as a CSS color value.

    Once set, changes to the CanvasGradient or CanvasPattern that

    was used will reect upon newly drawn content.

    Default is #00000

    fllStyle Gets or sets the current style used or flling shapes. Followsthe same rules as llStyle. Default is "#00000".

    The CanvasGradient interace defnes the methods or creating linear andradial gradients. Once a gradient is created, stops are placed along it todene the color distribution. With no stops, the gradient is simply black.

    CanvasGradient Methods

    Method/Property Description

    addColorStop(oset,color)

    Adds a color stop to the gradient at the given oset. The oset

    goes rom 0 to 1. The color is a string representation o a valid CSS

    color value.

    context. Creates and returns a CanvasGradient object that representsa linear gradient that paints along the coordinates given. Iscalled on an instance o a Canvas2DContext.

  • 8/3/2019 RC151 010d Html5 Canvas

    5/7

    4 HTML5 Canvas

    DZone, Inc. | www.dzone.com

    CanvasPattern Methods

    Method/Property Description

    context.createPattern(image,repetition)

    Creates and returns a CanvasPattern object that uses the givenimage and repeats in the directions defned by the repetitionargument.

    The frst argument must be an Image, a Canvas, or a V ideoelement.

    The allowed values or the second argument are the stringsrepeat, repeat-x, repeat-y, and no-repeat. The defaultis repeat.

    Like the gradients, this method is called on an instance o aCanvas2DContext.

    Note that the CanvasGradient and CanvasPattern are distinct objects fromthe Canvas, but these gradients and patterns can only be created using aninstance o the Canvas2DContext.Example syntax:

    // creating a gradient that will display black to white along the linear path

    from (0,0) to (0,150)// where context is an instance of Canvas2DContextvar gradient = context.createLinearGradient(0,0,0,150);gradient.addColorStop(0, #000000);gradient.addColorStop(1, #FFFFFF);ctx.llStyle = gradient; // assignment to the contexts llStyle

    Line Styles

    Method/Property Description

    lineWidth Gets or sets the width o lines to be drawn. Deault 1.0.

    lineCap Gets or sets how the end o lines are to be drawn. Valid valuesare "butt", "round", and "square". Deault "butt".

    lineJoin Gets or sets how corners are drawn when two lines meet. Validvalues are "bevel", "round", and "miter. Default "miter".

    miterLimit Gets or sets the current miter limit ratio. Deault 10.0.

    Three gray lines drawn to the thin black line. From top to bottom, thelineCap property of each is butt, round, and square.

    Three paths, each drawn up to the thin black line and back down. Fromleft to right, the lineJoin property of each is miter, round, andbevel.

    Shadows

    Method/Property Description

    shadowColor Gets or sets the color o the shadow. Accepts any valid CSScolor string. Deault is transparent black.

    shadowOsetX Gets or sets the X offset. Pushes the shadow farther to theright. Deault 0.

    shadowOsetY Gets or sets the Y oset. Deault 0.

    shadowBlur Gets or sets the level o blurring eect. The lower the value,the sharper the edge o the shadow. Deault 0.

    Shadows are smart, emulating the drawn pixels precisely so that if textis drawn, the shadow will look just as the text does. Additionally, shadowsare not aected by the transormation matrix.

    A square drawn with a shadowOffsetX and shadowOffsetY of 15. Theshadow is drawn evenly 15 pixels offset in both axes. To the right is thesame square drawn with the same shadowOffsetX and Y, but the contextwas rotated about the squares center.

    This means that if you were to rotate the square 180 degrees, the shadowwould be in the exact same place as i the square were not rotated atall. There is an advantage to having shadows drawn unaected by thetransormation matrix. I you draw several objects, some rotated and somenot, you typically want the shadows to all stay in the same direction, givingthe proper illusion o a l ight-source. I the shadows were aected by thetransormation matrix, it would look as i there is no singular light sourcebut shadows going in every direction!

    Paths

    Method/Property Description

    beginPath() Erases all current subpaths in preparation or drawing a newpath.

    closePath() Closes the subpath by drawing a straight line rom the currentpoint to the initial point.

    moveTo(x, y) Creates a new subpath at the given point. Typically used toplace the starting point, or to draw unconnected paths.

    lineTo(x, y) Draw a line to the given point.

    quadraticCurveTo(cpx,cpy, x, y)

    Draw a quadratic curve with the given control point (cpx, cpy)to the given point (x, y)

    bezierCurveTo(cp1x,cp1y, cp2x, cp2y, x, y)

    Draw a bezier curve described by the two given sets o controlpoints and a given end point.

    arcTo(x1, y1, x2, y2,radius)

    Draw an arc with the given control points and radius, con-nected to the previous point via a straight line.

    arc(in double x, y,radius, startAngle,endAngle, [anticlock-wise])

    Draw an arc described by the circumerence o the circle de-scribed by the given arguments, starting at the startAngle andending at the endAngle , going in the given direction (deault-ing to clockwise i the last argument is let blank)

    rect(x, y, w, h) Add the closed subpath in the shape o a rectangle.

    fll() Fills all described subpaths with the current fllStyle.

    stroke() Strokes all described subpaths with the current strokeStyle.

    Filling a path will fll all o the subpaths o the current path. It flls themaccording to the non-zero winding number rule. When a ll is called, allopen subpaths get implicitly closed.

    Text and Images

    Method/Property Descriptionont Gets or sets the current ont settings. Must be a string that will

    be parsed as a CSS ont property.

    textAlign Gets or sets the text alignment. Possible values are "start","end", "let", "right", and "center". Deault is "start".

    textBaseline Gets or sets the baseline setting. Can be "top", "hanging","middle", "alphabetic", "ideographic", or "bottom". Deaultis "alphabetic".

    fllText(text, x, y, [,maxWidth])

    Fills the given text at a given position using the llStyle. Notethat the position at the textBaseline.

    strokeText(text, x, y, [,maxWidth])

    Strokes the text at a given position using the strokeStyle.

    drawImage(image,dx, dy)

    Draws a given image to the context at the given position. Seebelow.

    drawImage(image, dx,dy, dw, dh)

    Draws a given image to the context at the given position, scal-ing the image to the given width and height.

  • 8/3/2019 RC151 010d Html5 Canvas

    6/7

    5 HTML5 Canvas

    DZone, Inc. | www.dzone.com

    drawImage(image,sx, sy, sw, sh, dx, dy,dw, dh)

    Draws a section o a given image that is described by the pointand size given by (sx, sy, sw, sh), which is in turn drawn to thecontext at the point and size given by (dx, dy, dw, dh).

    Drawing and measuring text are among some o the slowest operationson Canvas, so it is among the frst places you should start fddling aroundor more perormance. It can oten be the case that storing the resultof a drawText in a PNG or a separate in-memory Canvas will improveperormance.

    The six different baselines, all drawn on the same Y-value, represented bythe black line. Alphabetic shown in red is the default.

    All three drawImage unctions take either an image, Canvas, or videoelement. Even i you never think o your app asdrawing any images ontoyour Canvas, these methods can come in very handy. For perormancereasons, you may fnd yoursel making Canvases in memory and drawingportions o your screen to them or vice versa. I you want a miniature

    overlay above your complex Canvas, you can call drawImage on yourCanvas context and pass in its own Canvas to create such a mini-map.

    The optional arguments to drawImage allow us to paint a portion of animage onto the canvas and force it to scale into the width and height dwand dh.

    Pixel Manipulation

    Method/Property Description

    createImageData(sw, sh) Returns an ImageData object with the given widthand height. The ImageDatas pixels are flled withtransparent black.

    createImageData(imagedata) Returns an ImageData object with the same widthand height as the given ImageData. All o thereturned ImageDatas pixels are transparent black.

    putImageData(imagedata, dx,dy,[, dirtyX, dirtyY, dirtyWidth,dirtyHeight])

    Paints a given ImageData onto the Canvas. I adirty rectangle is provided, only the pixels fromthat rectangle are painted.

    The pixels painted by putImageData are precise; globalAlpha andglobalCompositeOperation are not taken into account during theirpainting. Because of this, you do not want to use putImageData to paintpart o a Canvas to another Canvas as the transparent region will becarried over, clobbering whatever was there beore.

    Another reason to always consider drawImage beore using putImageDatais the performance difference. Working with ImageData is very slowcompared to calls to drawImage, so only use it i you absolutely need todo per-pixel operations (such as making an eyedropper tool).

    Also note that the optional dirty rectangle arguments for putImageDataare not implemented on all browsers. I you use it, make sure all browserstargeted have the unctionality.

    ImageData Properties

    Property Description

    width Gets the width o the ImageData object.

    height Gets the height o the ImageData object.

    data Returns a one-dimensional array containing the data

    in RGBA order, as integers in the range 0 to 255.

    The ImageData.data property returns an array where each pixel isrepresented by four indices. The rst pixels R, G, B, and Alpha valuesare thus indicated by data[0], data[1], data[2], data[3]. The second pixel isindicated by the indices 4 to 7 and so on. The order of the pixels is fromlet to right, top to bottom, just like reading text in let-to-right languages.

    TIPS FOR YOUR CANVAS APP

    Web developers are no strangers to quirks, and Canvas has its ownlaundry list of idiosyncrasies. Below are a few things to keep in mind as

    you make Canvas apps.

    There are several valid ways to clear a Canvas, but some are muchfaster than others. Below are three common ways with their differencesdescribed:

    can.width = can.width;

    Setting the Canvas width attribute equal to itsel will not only clear theCanvas but also clear the entire state (see State and transormationssection or what this entails). This is useul i you want a ull reset, but it istypically slow.

    ctx.clearRect(0, 0, can.width, can.height);

    The above merely clears the pixels on the screen; but i the transormation

    is not identity, it may not work as intended.

    ctx.save();ctx.setTransform(1, 0, 0, 1, 0, 0);ctx.clearRect(0, 0, can.width, can.height);ctx.restore();

    This is a good way to clear the Canvas while keeping all the state dataintact. The perormance dierence between the use o clearRect andsetting Canvas width equal to itsel varies wildly between browsers. Youshould benchmark oten on the platorms you are targeting.

    There are different ways of doing operations that have differentperormance eects on dierent browsers. For example, in the Canvas-clearing example above, it is always aster to not set Canvas width equalto itsel with the lone exception o Saari 5, in which that method istwo orders o magnitude aster. I you are targeting a specifc browser,

    especially a phone or tablet, you should be sure to tailor your perormancecomputations around it.

    In a draw loop, it is often benecial to try and draw only the objectsthat have changed and (perhaps) any objects that intersect their bounds.However, depending on the application, this is not always the case. Inothing in the scene has changed, it is o course always the case thatskipping out on drawing entirely is much aster.

    Use requestAnimationFrame on browsers that support it. It will ensurethat animation is not occurring on non-active tabs with Canvas elements,which can save battery lie on phones and tablets.

    Draw and hit test only what is on the screen.

    Hit testing only what is on the screen.

  • 8/3/2019 RC151 010d Html5 Canvas

    7/7

    http://refcardz.dzone.com/