Sophie

Sophie

distrib > Fedora > 18 > x86_64 > by-pkgid > ff187cb994c94c614ecc64c5a8528b1b > files > 6937

qt-doc-4.8.5-10.fc18.noarch.rpm

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- chapter_canvas.qdoc -->
  <title>Qt 4.8: QtWebKit Guide - Canvas Graphics</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />
  <script src="scripts/jquery.js" type="text/javascript"></script>
  <script src="scripts/functions.js" type="text/javascript"></script>
  <link rel="stylesheet" type="text/css" href="style/superfish.css" />
  <link rel="stylesheet" type="text/css" href="style/narrow.css" />
  <!--[if IE]>
<meta name="MSSmartTagsPreventParsing" content="true">
<meta http-equiv="imagetoolbar" content="no">
<![endif]-->
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie6.css">
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie7.css">
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="style/style_ie8.css">
<![endif]-->

<script src="scripts/superfish.js" type="text/javascript"></script>
<script src="scripts/narrow.js" type="text/javascript"></script>

</head>
<body class="" onload="CheckEmptyAndLoadList();">
 <div class="header" id="qtdocheader">
    <div class="content"> 
    <div id="nav-logo">
      <a href="index.html">Home</a></div>
    <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a>
    <div id="narrowsearch"></div>
    <div id="nav-topright">
      <ul>
        <li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li>
        <li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li>
        <li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/">
          DOC</a></li>
        <li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li>
      </ul>
    </div>
    <div id="shortCut">
      <ul>
        <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li>
        <li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS        </a></li>
      </ul>
     </div>
 <ul class="sf-menu" id="narrowmenu"> 
             <li><a href="#">API Lookup</a> 
                 <ul> 
                     <li><a href="classes.html">Class index</a></li> 
           <li><a href="functions.html">Function index</a></li> 
           <li><a href="modules.html">Modules</a></li> 
           <li><a href="namespaces.html">Namespaces</a></li> 
           <li><a href="qtglobal.html">Global Declarations</a></li> 
           <li><a href="qdeclarativeelements.html">QML elements</a></li> 
             </ul> 
             </li> 
             <li><a href="#">Qt Topics</a> 
                 <ul> 
                        <li><a href="qt-basic-concepts.html">Programming with Qt</a></li>  
                        <li><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li>  
                        <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li>  
                        <li><a href="supported-platforms.html">Supported Platforms</a></li>  
                        <li><a href="technology-apis.html">Qt and Key Technologies</a></li>  
                        <li><a href="best-practices.html">How-To's and Best Practices</a></li>  
              </ul> 
                 </li> 
                 <li><a href="#">Examples</a> 
                     <ul> 
                       <li><a href="all-examples.html">Examples</a></li> 
                       <li><a href="tutorials.html">Tutorials</a></li> 
                       <li><a href="demos.html">Demos</a></li> 
                       <li><a href="qdeclarativeexamples.html">QML Examples</a></li> 
                </ul> 
                     </li> 
                 </ul> 
    </div>
  </div>
  <div class="wrapper">
    <div class="hd">
      <span></span>
    </div>
    <div class="bd group">
      <div class="sidebar">
        <div class="searchlabel">
          Search index:</div>
        <div class="search" id="sidebarsearch">
          <form id="qtdocsearch" action="" onsubmit="return false;">
            <fieldset>
              <input type="text" name="searchstring" id="pageType" value="" />
 <div id="resultdialog"> 
 <a href="#" id="resultclose">Close</a> 
 <p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p> 
 <p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span>&nbsp;results:</p> 
 <ul id="resultlist" class="all"> 
 </ul> 
 </div> 
            </fieldset>
          </form>
        </div>
        <div class="box first bottombar" id="lookup">
          <h2 title="API Lookup"><span></span>
            API Lookup</h2>
          <div  id="list001" class="list">
          <ul id="ul001" >
              <li class="defaultLink"><a href="classes.html">Class index</a></li>
              <li class="defaultLink"><a href="functions.html">Function index</a></li>
              <li class="defaultLink"><a href="modules.html">Modules</a></li>
              <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li>
              <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li>
              <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li>
            </ul> 
          </div>
        </div>
        <div class="box bottombar" id="topics">
          <h2 title="Qt Topics"><span></span>
            Qt Topics</h2>
          <div id="list002" class="list">
            <ul id="ul002" >
               <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> 
               <li class="defaultLink"><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> 
               <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> 
               <li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li>  
               <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> 
               <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> 
            </ul>  
          </div>
        </div>
        <div class="box" id="examples">
          <h2 title="Examples"><span></span>
            Examples</h2>
          <div id="list003" class="list">
        <ul id="ul003">
              <li class="defaultLink"><a href="all-examples.html">Examples</a></li>
              <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li>
              <li class="defaultLink"><a href="demos.html">Demos</a></li>
              <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li>
            </ul> 
          </div>
        </div>
      </div>
      <div class="wrap">
        <div class="toolbar">
          <div class="breadcrumb toolblock">
            <ul>
              <li class="first"><a href="index.html">Home</a></li>
              <!--  Breadcrumbs go here -->
<li>QtWebKit Guide - Canvas Graphics</li>
            </ul>
          </div>
          <div class="toolbuttons toolblock">
            <ul>
              <li id="smallA" class="t_button">A</li>
              <li id="medA" class="t_button active">A</li>
              <li id="bigA" class="t_button">A</li>
              <li id="print" class="t_button"><a href="javascript:this.print();">
                <span>Print</span></a></li>
            </ul>
        </div>
        </div>
        <div class="content mainContent">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#canvas-graphics">Canvas Graphics</a></li>
<li class="level1"><a href="#accessing-the-rendering-context">Accessing the Rendering Context</a></li>
<li class="level1"><a href="#drawing-shapes">Drawing Shapes</a></li>
<li class="level2"><a href="#drawing-rectangles">Drawing Rectangles</a></li>
<li class="level2"><a href="#drawing-lines">Drawing Lines</a></li>
<li class="level2"><a href="#drawing-arcs">Drawing Arcs</a></li>
<li class="level1"><a href="#compositing">Compositing</a></li>
<li class="level1"><a href="#saving-and-exporting-canvas-drawings-as-image-files">Saving and Exporting Canvas Drawings as Image Files</a></li>
<li class="level1"><a href="#drawing-text">Drawing Text</a></li>
<li class="level1"><a href="#working-with-images">Working with Images</a></li>
<li class="level2"><a href="#creating-patterns-with-images">Creating Patterns with Images</a></li>
<li class="level1"><a href="#applying-colors">Applying Colors</a></li>
<li class="level2"><a href="#applying-gradients">Applying Gradients</a></li>
<li class="level2"><a href="#applying-shadows">Applying Shadows</a></li>
<li class="level1"><a href="#transforming-graphics">Transforming Graphics</a></li>
<li class="level2"><a href="#translating-the-canvas-origin">Translating the Canvas Origin</a></li>
<li class="level2"><a href="#rotating-the-canvas">Rotating the Canvas</a></li>
<li class="level2"><a href="#scaling-the-canvas-grid">Scaling the Canvas Grid</a></li>
<li class="level2"><a href="#manipulating-the-transformation-matrix">Manipulating the Transformation Matrix</a></li>
<li class="level1"><a href="#canvas-animations">Canvas Animations</a></li>
</ul>
</div>
<h1 class="title">QtWebKit Guide - Canvas Graphics</h1>
<span class="subtitle"></span>
<!-- $$$qtwebkit-guide-canvas.html-description -->
<div class="descr"> <a name="details"></a>
<a name="canvas-graphics"></a>
<h2>Canvas Graphics</h2>
<p>This section of the <a href="qtwebkit-guide.html">QtWebKit Guide</a> serves as an introduction to the <a href="http://dev.w3.org/html5/canvas-api/canvas-2d-api.html">HTML5 Canvas API</a> features of <a href="qtwebkit.html">QtWebKit</a>.</p>
<p>The <a href="http://dev.w3.org/html5/canvas-api/canvas-2d-api.html">HTML5 Canvas API</a> enables you to draw within a Web page or Web App using JavaScript. After you define a rectangle that serves as your drawing canvas, you can draw straight and curved lines, simple and complex shapes, graphs, and referenced graphic images. You can add text, color, shadows, gradients, and patterns. The canvas API also enables you to save or export the canvas as a .png or .jpeg image file.</p>
<p>To define the drawing area, set the <tt>width</tt> and <tt>height</tt> of a <tt>&lt;canvas&gt;</tt> element. For example, the following sets a drawing area with a height of 100 pixels and width of 200 pixels:</p>
<pre class="cpp"> <span class="operator">&lt;</span>canvas id<span class="operator">=</span><span class="string">&quot;mycanvas&quot;</span> width<span class="operator">=</span><span class="string">&quot;100&quot;</span> height<span class="operator">=</span><span class="string">&quot;200&quot;</span><span class="operator">&gt;</span><span class="operator">&lt;</span><span class="operator">/</span>canvas<span class="operator">&gt;</span></pre>
<p>By default, <tt>canvas</tt> elements are sized 150 pixels high and 300 pixels wide. You can also set the size of the canvas using CSS:</p>
<pre class="cpp"> canvas { height : <span class="number">200px</span>; width : <span class="number">100px</span>; }</pre>
<p>The <tt>canvas</tt> element is transparent and has no visible borders until you <a href="#accessing-the-rendering-context">access the 2D rendering context</a>.</p>
<p>Resetting the width or height of an existing canvas erases its contents and resets all the context properties of the canvas to their default values.</p>
<a name="accessing-the-rendering-context"></a>
<h2>Accessing the Rendering Context</h2>
<p>The rendering <b>context</b> defines the methods and attributes needed to draw on the canvas. <a href="qtwebkit.html">QtWebKit</a> currently supports the two-dimensional rendering context. The following assigns the canvas rendering context to a <tt>context</tt> variable:</p>
<pre class="cpp"> var context <span class="operator">=</span> canvas<span class="operator">.</span>getContext(<span class="string">&quot;2d&quot;</span>)</pre>
<p>The 2d context renders the canvas as a coordinate system whose origin (0,0) is at the top left corner, as shown in the figure below. Coordinates increase along the <tt>x</tt> axis from left to right and along the <tt>y</tt> axis from top to bottom of the canvas.</p>
<p class="centerAlign"><img src="images/canvas_context.gif" alt="" /></p><a name="drawing-shapes"></a>
<h2>Drawing Shapes</h2>
<p>The 2D rendering context supports rectangles, lines, and arcs, which you can combine to build complex shapes and graphic images.</p>
<a name="drawing-rectangles"></a>
<h3>Drawing Rectangles</h3>
<p>The rectangle is the only geometric shape that is built in to the canvas API. You can draw an outline of a rectangle, a filled rectangle, and a filled rectangle with clear parts. You do not have to create a path to draw a rectangle.</p>
<p>To draw an outline of a rectangle, use the <tt>strokeRect()</tt> method.</p>
<p>To draw a filled rectangle, use the <tt>fillRect()</tt> method. The default fill color is black.</p>
<p>To clear part of a filled rectangle, use the <tt>clearRect()</tt> method.</p>
<p>Each method accepts the following series of arguments:</p>
<ul>
<li><tt>x</tt> is the position on the canvas to the right of the origin (0,0) of the top left corner of the rectangle</li>
<li><tt>y</tt> is the position on the canvas below the origin of the top left corner of the rectangle</li>
<li><tt>width</tt> is the width of the rectangle to be drawn</li>
<li><tt>height</tt> is the height of the rectangle to be drawn</li>
</ul>
<p>For example, the following code draws concentric rectangles:</p>
<pre class="cpp">     var context <span class="operator">=</span> canvas<span class="operator">.</span>getContext(<span class="string">&quot;2d&quot;</span>);
     canvas<span class="operator">.</span>strokeRect(<span class="number">50</span><span class="operator">,</span><span class="number">50</span><span class="operator">,</span><span class="number">50</span><span class="operator">,</span><span class="number">50</span>);
     canvas<span class="operator">.</span>fillRect(<span class="number">60</span><span class="operator">,</span><span class="number">60</span><span class="operator">,</span><span class="number">30</span><span class="operator">,</span><span class="number">30</span>);
     canvas<span class="operator">.</span>clearRect(<span class="number">70</span><span class="operator">,</span><span class="number">70</span><span class="operator">,</span><span class="number">10</span><span class="operator">,</span><span class="number">10</span>);</pre>
<p class="centerAlign"><img src="images/canvas_rectangles.gif" alt="" /></p><a name="drawing-lines"></a>
<h3>Drawing Lines</h3>
<p>To draw a line, you first have to <i>&quot;put your pencil down&quot;</i> on the canvas by creating a path. The <tt>context.beginPath()</tt> method sets a new path in the canvas. Each line that you draw is stored as a sub-path. Sub-paths can be closed to form a shape, or they can be left open. Each time you want to draw a new shape, you have to call the <tt>beginPath()</tt> method to reset the current path.</p>
<p>After calling <tt>beginPath()</tt>, you set your starting position on the canvas by calling the <tt>context.moveTo(x,y)</tt> method. The <tt>moveTo(x,y)</tt> method creates a new subpath on the canvas that begins at the Cartesian point <tt>(x,y)</tt>.</p>
<p>To draw a straight line, call the <tt>context.lineTo(x,y)</tt> method. This adds the point (x,y) to the current subpath and connects it to the previous subpath by a straight line. In other words, (x,y) are the coordinates of the line's endpoint. For example:</p>
<pre class="cpp">     context<span class="operator">.</span>beginPath();
     context<span class="operator">.</span>moveTo(<span class="number">10</span><span class="operator">,</span><span class="number">10</span>);
     context<span class="operator">.</span>lineTo(<span class="number">30</span><span class="operator">,</span><span class="number">30</span>);</pre>
<p>To get the <i>pencil</i> to actually draw on the canvas, first use the <tt>strokeStyle</tt> property to set the color to a value such as black (<tt>#000</tt>):</p>
<pre class="cpp">     context<span class="operator">.</span>strokeStyle(<span class="preprocessor">#000);</span></pre>
<p>(The <tt>strokeStyle</tt> property can be a CSS color, a pattern, or a gradient.) Then use the <tt>context.stroke()</tt> method to actually draw the line on the canvas:</p>
<pre class="cpp">     context<span class="operator">.</span>stroke();</pre>
<p>This produces the image below. The numeric coordinates are added for clarity but are not part of the image drawn by the code:</p>
<p class="centerAlign"><img src="images/canvas_lineStrokeTo.gif" alt="" /></p><p>To create a shape, call the <tt>context.closePath()</tt> method:</p>
<pre class="cpp">     context<span class="operator">.</span>closePath();
     context<span class="operator">.</span>moveTo(<span class="number">10</span><span class="operator">,</span><span class="number">10</span>);        <span class="comment">// starting point</span>
     context<span class="operator">.</span>lineTo(<span class="number">30</span><span class="operator">,</span><span class="number">30</span>);        <span class="comment">// specify first line</span>
     context<span class="operator">.</span>moveTo(<span class="number">30</span><span class="operator">,</span><span class="number">30</span>);        <span class="comment">// move to end of first line</span>
     context<span class="operator">.</span>lineTo(<span class="number">60</span><span class="operator">,</span><span class="number">10</span>);        <span class="comment">// specify second line</span>
     context<span class="operator">.</span>moveTo(<span class="number">60</span><span class="operator">,</span><span class="number">10</span>);        <span class="comment">// move to end of second line</span>
     context<span class="operator">.</span>lineTo(<span class="number">10</span><span class="operator">,</span><span class="number">10</span>);        <span class="comment">// specify third line to close triangle</span>
     context<span class="operator">.</span>strokeStyle(<span class="string">&quot;#000&quot;</span>);    <span class="comment">// use black color for lines</span>
     context<span class="operator">.</span>stroke();        <span class="comment">// draws the triangle lines on the canvas</span></pre>
<p>To fill the shape, use the <tt>fillstyle</tt> property and the <tt>fill()</tt> method:</p>
<pre class="cpp">     context<span class="operator">.</span>fillStyle(<span class="string">&quot;#FF0000&quot;</span>); <span class="comment">// use red color for fill</span>
     context<span class="operator">.</span>fill(); <span class="comment">// fill the triangle</span></pre>
<p>The commands, if coded fully, would create the shape below:</p>
<p class="centerAlign"><img src="images/canvas_closepath.gif" alt="" /></p><p><b>Note:</b> It is not necessary to close the path when calling the <tt>fill()</tt> method. Calling <tt>fill()</tt> closes the path and creates the completed shape.</p>
<p>You can draw lines of various widths, endcap types, and joining options by configuring the following attributes:</p>
<ul>
<li><tt>lineWidth</tt> sets the thickness of the current line. The value can be any number greater than <tt>0</tt>. For example, <tt>context.lineWidth = 10</tt> sets the line thickness to <tt>10</tt> units. The default value is <tt>1</tt> unit, which is not the same as <tt>1</tt> <i>pixel</i>. Instead, the line is centered on the current path, with half its thickness on each side of the path.</li>
<li><tt>lineCap</tt> sets the type of endpoint of the current line. The value can be either <tt>butt</tt>, <tt>square</tt>, or <tt>round</tt>. (The default value is <tt>butt</tt>.)<ul>
<li><tt>butt</tt>- the ends of the line abutt the line guide.</li>
<li><tt>square</tt> adds a box at both ends of the line.</li>
<li><tt>round</tt> adds a semicircle at both ends of the line.</li>
</ul>
</li>
<li><tt>lineJoin</tt> sets the style with which lines are joined. The value can be either <tt>bevel</tt>, <tt>round</tt>, or <tt>miter</tt>. (The default value is <tt>miter</tt>.)<ul>
<li><tt>bevel</tt> flattens the corners at which the lines join</li>
<li><tt>round</tt> rounds the corners at which the lines join</li>
<li><tt>miter</tt> joins the lines at a single point</li>
</ul>
</li>
<li><tt>miterLimit</tt> sets the <i>miter limit ratio</i>. The value can be any number greater than <tt>0</tt>. The miter limit ratio determines how far the connection point of the outside of the lines can be from the connection point of the inside of the lines. (The default value is <tt>10</tt>.)</li>
</ul>
<p class="centerAlign"><img src="images/canvas_linecap.png" alt="" /></p><a name="drawing-arcs"></a>
<h3>Drawing Arcs</h3>
<p>To draw an arc, you begin with the same steps your followed to create a line:</p>
<ol class="1">
<li>Call the <tt>context.beginPath()</tt> method to <i>&quot;put your pencil down&quot;</i> on the canvas and set a new path.</li>
<li>Call the <tt>context.moveTo(x,y)</tt> method to set your starting position on the canvas at the point (x,y).</li>
<li>To draw an arc or circle, call the <tt>context.arcTo(x1,y1,x2,y2,radius)</tt> method. This adds an arc with starting point <tt>(x1,y1)</tt>, ending point <tt>(x2,y2)</tt>, and radius <tt>radius</tt> to the current subpath and connects it to the previous subpath by a straight line.<p class="centerAlign"><img src="images/canvas_arcTo.png" alt="" /></p></li>
<li>An alternative way to draw an arc or circle is to call the <tt>context.arc(x,y,radius,startAngle,endAngle,anticlockwise)</tt> method. This adds an arc to the current subpath that lies on the circumference of the circle whose center is at the point (x,y) and whose radius is <tt>radius</tt>.<p class="centerAlign"><img src="images/canvas_arcTo2.png" alt="" /></p><p>Both <tt>startAngle</tt> and <tt>endAngle</tt> are measured from the x axis in units of radians.</p>
<p>A complete circle is <tt>360</tt> degrees, or 2&Pi; radians. A semicircle is <tt>180</tt> degrees, or &Pi; radians. The number of radians is the number of degrees multiplied by &Pi;/180, expressed in JavaScript as:</p>
<pre class="cpp">     var radians <span class="operator">=</span> (Math<span class="operator">.</span>PI<span class="operator">/</span><span class="number">180</span>)<span class="operator">*</span>degrees;</pre>
<p class="centerAlign"><img src="images/canvas_startAngle.png" alt="" /></p><p><tt>anticlockwise</tt> has the value <tt>TRUE</tt> for each arc in the figure above because they are all drawn in the counterclockwise direction.</p>
</li>
<li>To create a shape, call the <tt>context.closePath()</tt> method. This marks the current subpath as closed and draws a straight line from the current point to the first point in the path.</li>
<li>To draw only the outline of the shape, call the <tt>context.stroke()</tt> method.</li>
<li>To fill in the shape, call the <tt>context.fill()</tt> method.</li>
<li>To set the color of the fill, set the <tt>strokeStyle</tt>. For example, the code<pre class="cpp">     context<span class="operator">.</span>strokeStyle <span class="operator">=</span> <span class="string">&quot;#FF0000&quot;</span>;</pre>
<p>sets the fill color to red.</p>
</li>
</ol>
<p><b>Note:</b> It is not necessary to close the path if you are going to call the <tt>fill()</tt> method. The fill closes the path and creates the completed shape.</p>
<p>To create complex shapes, combine lines and arcs:</p>
<ol class="1">
<li>Call the <tt>context.beginPath()</tt> method to <i>&quot;put your pencil down&quot;</i> on the canvas and set a new path.</li>
<li>Call the <tt>context.moveTo(x,y)</tt> method to set your starting position on the canvas at the point (x,y).</li>
<li>Draw any combination of lines and arcs by calling the <tt>lineTo</tt>, <tt>arcTo</tt>, <tt>arc</tt>, <tt>moveTo</tt>, <tt>closePath</tt>, <tt>stroke</tt>, and <tt>fill</tt> methods and setting the line attributes and fill colors as described above.</li>
</ol>
<p>You can also create complex shapes by removing portions of the shapes you draw. The <tt>clip()</tt> method creates a clipping path that defines the area along which your &quot;scissor&quot; will cut. Any parts of the shape outside the clipping path are not displayed. To create a complex shape using the <tt>clip()</tt> method:</p>
<ol class="1">
<li>Call the <tt>context.beginPath()</tt> method to set the clipping path.</li>
<li>Define the clipping path by calling any combination of the <tt>lineTo</tt>, <tt>arcTo</tt>, <tt>arc</tt>, <tt>moveTo</tt>, and <tt>closePath</tt> methods.</li>
<li>Call the <tt>context.clip()</tt> method.</li>
</ol>
<p>The new shape displays. The following shows how a clipping path can modify how an image displays:</p>
<p class="centerAlign"><img src="images/canvas_clip-complex.png" alt="" /></p><a name="compositing"></a>
<h2>Compositing</h2>
<p>You can build complex shapes by drawing shapes on top of each other. It is also possible to draw shapes behind existing shapes and to mask parts of shapes by using <i>compositing operations</i>. The <tt>globalCompositeOperation</tt> attribute sets the way shapes can be combined.</p>
<p>The first shape drawn on the canvas to which additional shapes are added is called the <i>destination</i> shape. The shape drawn on the canvas afterwards to create the composite image is called the <i>source</i> shape. The value of the <tt>globalCompositeOperation</tt> attribute must be set to one of the following:</p>
<ul>
<li><tt>source-over</tt> displays the source (newer) shape over the destination (older) shape unless the source shape is transparent. (This is the default value)</li>
<li><tt>source-in</tt> displays only the portion of the source shape that is opaque and overlaps the destination shape. Everything else is transparent.</li>
<li><tt>source-out</tt> displays only the portion of the source shape that does not overlap the destination shape.</li>
<li><tt>source-atop</tt> displays only the portion of the opaque source shape that overlaps the destination shape and the portion of the destination shape that is not covered by the opaque source shape.</li>
<li><tt>destination-over</tt> displays the destination shape over the source shape. In areas where both shapes are opaque and overlap, the older shape displays.</li>
<li><tt>destination-in</tt> displays only the portion of the destination shape that is opaque and overlaps the source shape. Everything else is transparent. The source (newer) shape is not visible.</li>
<li><tt>destination-out</tt> displays only the portion of the destination shape that does not overlap the source shape. The source shape is not visible.</li>
<li><tt>destination-atop</tt> displays only the portion of the opaque destination shape that overlaps the source shape and the portion of the source shape that is not covered by the opaque destination shape.</li>
<li><tt>lighter</tt> displays both the source and destination shapes. Where the shapes overlap, the their color values are added, producing a lighter color.</li>
<li><tt>copy</tt> displays only the source shape. The destination shape is ignored.</li>
<li><tt>xor</tt> displays both the source and the destination shapes except the areas of overlap, in which both shapes are completely transparent.</li>
</ul>
<p>The following figure shows the various compositing effects:</p>
<p class="centerAlign"><img src="images/canvas_composite.png" alt="" /></p><a name="saving-and-exporting-canvas-drawings-as-image-files"></a>
<h2>Saving and Exporting Canvas Drawings as Image Files</h2>
<p>You can save or export your canvas drawings as .png or .jpeg image files by calling the <tt>toDataURL()</tt> method:</p>
<pre class="cpp"> canvas<span class="operator">.</span>toDataURL(<span class="operator">[</span>type<span class="operator">,</span> <span class="operator">.</span><span class="operator">.</span><span class="operator">.</span><span class="operator">]</span>)</pre>
<p>where:</p>
<ul>
<li><tt>type</tt> is the MIME type to which you want to save or export your canvas. Possible values are:<ul>
<li><tt>&quot;image\png&quot;</tt> (Default value)</li>
<li><tt>&quot;image\jpeg&quot;</tt></li>
</ul>
</li>
<li><tt>...</tt> represents additional arguments that depend on the MIME type.<ul>
<li>If <tt>type</tt> is <tt>png</tt>, this argument is <tt>&quot; &quot;</tt></li>
<li>If <tt>type</tt> is <tt>jpeg</tt>, this argument is the desired quality level of the image. The value is a number in the range 0.0 to 1.0, inclusive.</li>
</ul>
</li>
</ul>
<a name="drawing-text"></a>
<h2>Drawing Text</h2>
<p>You can draw text on your canvas by setting the following font attributes on the 2d drawing context:</p>
<ul>
<li><tt>font</tt> refers to any font, expressed the same way as in CSS properties. This attribute's value can include any font style, variant, weight, size, height, and family. For example:<pre class="cpp">     context<span class="operator">.</span>font <span class="operator">=</span> <span class="string">&quot;12pt Arial&quot;</span>;</pre>
<p>The default value is <tt>10px sans-serif</tt>.</p>
<p>If you set the <tt>font</tt> attribute to a relative font size, the browser multiplies it by the computed font size of the <tt>&lt;canvas&gt;</tt> element itself. For example:</p>
<pre class="cpp">     context<span class="operator">.</span>font <span class="operator">=</span> <span class="string">&quot;200%&quot;</span>;</pre>
</li>
<li><tt>textAlign</tt> specifies the alignment of the text. The values can be one of the following:<ul>
<li><tt>left</tt> for left-aligned text</li>
<li><tt>right</tt> for right-aligned text</li>
<li><tt>center</tt> for text that is centered within each line</li>
<li><tt>start</tt> (default) - the text is aligned at the beginning of the line. Text is left- or right-justified based on locale-specific writing method: left when text is left-to-right, right when text is right-to-left.</li>
<li><tt>end</tt> - the text is aligned at the end of the line, either left or right depending on locale-specific writing method.</li>
</ul>
</li>
<li><tt>textBaseline</tt> specifies the position at which text is drawn relative to a baseline. The figure below, from <a href="http://dev.w3.org/html5/canvas-api/canvas-2d-api.html">HTML5 Canvas API</a>, illustrates the possible values for the <tt>textBaseline</tt> attribute:<ul>
<li><tt>top</tt> is the top of the em square, which approximates the top of the glyphs in a font</li>
<li><tt>hanging</tt> specifies a hanging baseline, where the tops of some glyphs are anchored.</li>
<li><tt>middle</tt> is the mid-point of the em square</li>
<li><tt>alphabetic</tt> (default) is the anchor point of many alphabetic characters</li>
<li><tt>ideographic</tt> is the anchor point of many ideograms, such as the characters used in the writing systems of many Asian languages</li>
<li><tt>bottom</tt> is the bottom of the em square</li>
</ul>
</li>
</ul>
<p class="centerAlign"><img src="images/canvas_text.png" alt="" /></p><p>To draw text on a canvas:</p>
<ol class="1">
<li>Set the <tt>font</tt> attribute on the drawing context. For example:<pre class="cpp">     context<span class="operator">.</span>font <span class="operator">=</span> <span class="string">&quot;bold 11px arial&quot;</span></pre>
</li>
<li>Measure the text that you want to draw by calling the <tt>measureText</tt> method:<pre class="cpp">     TextMetrics measureText(<span class="string">&quot;Text to draw&quot;</span>);</pre>
<p>where <tt>TextMetrics</tt> is the object returned. Its <tt>width</tt> attribute is the width, in pixels, that the <tt>&quot;Text to draw&quot;</tt> would be when drawn with the font specified by the <tt>font</tt> attribute.</p>
</li>
<li>Call either of the following methods:<ul>
<li><tt>fillText</tt> draws the text with the font style specified by the <tt>font</tt> attribute, the alignment specified by the <tt>textAlign</tt> attribute, and the baseline specified by the <tt>textBaseline</tt> attribute. For example:<pre class="cpp">     context<span class="operator">.</span>fillText(<span class="string">&quot;Text to draw&quot;</span><span class="operator">,</span>x<span class="operator">,</span>y<span class="operator">,</span>maximumWidth);</pre>
<p>where <tt>x</tt> and <tt>y</tt> are the coordinates at which the drawing begins (the anchor point), and <tt>maximumWidth</tt> is the maximum width of the text string (optional). If the <tt>width</tt> returned in step 2 is larger than the <tt>maximumWidth</tt>, the font is scaled down until the width of the text string is less than the <tt>maximumWidth</tt> specified.</p>
<p>If you don't specify the <tt>font</tt> attribute, the text inherits the font size and style of the <tt>&lt;canvas&gt;</tt> element itself.</p>
</li>
<li><tt>strokeText</tt> is the same as the <tt>fillText</tt> method, except that a stroke style is applied to the text instead of a fill style, creating outlines of glyphs. For example:<pre class="cpp"> context<span class="operator">.</span>fillText(<span class="string">&quot;Text to stroke&quot;</span><span class="operator">,</span>x<span class="operator">,</span>y<span class="operator">,</span>maximumWidth);</pre>
</li>
</ul>
</li>
</ol>
<a name="working-with-images"></a>
<h2>Working with Images</h2>
<p>You can insert existing images onto your canvas, you can scale or crop them, and you can combine them to create composite images. You can also draw new images by creating an <tt>Image()</tt> object with JavaScript.</p>
<p>To insert an existing image onto a canvas, call the <tt>drawImage</tt> method:</p>
<pre class="cpp"> context<span class="operator">.</span>drawImage(image<span class="operator">,</span> dx<span class="operator">,</span> dy<span class="operator">,</span> dw<span class="operator">,</span> dh)</pre>
<p>where:</p>
<ul>
<li><tt>image</tt> is a reference to an HTML <tt>&lt;image&gt;</tt> or <tt>&lt;canvas&gt;</tt> element. The image must be fully loaded before you can draw it on the canvas. The reference cannot be a URL. Instead, it should be referenced using standard DOM methods such as <tt>document.images()</tt> or <tt>document.getElementById()</tt>. For example:<pre class="cpp"> <span class="operator">&lt;</span>canvas id<span class="operator">=</span><span class="string">&quot;demo1&quot;</span> width<span class="operator">=</span><span class="string">&quot;100&quot;</span> height<span class="operator">=</span><span class="string">&quot;150&quot;</span><span class="operator">&gt;</span><span class="operator">&lt;</span><span class="operator">/</span>canvas<span class="operator">&gt;</span>

 var canvas <span class="operator">=</span> document<span class="operator">.</span>getElementById(<span class="string">&quot;demo1&quot;</span>);
 var context <span class="operator">=</span> canvas<span class="operator">.</span>getContext(<span class="string">&quot;2d&quot;</span>);</pre>
</li>
<li><tt>dx</tt> is the x coordinate of the upper left corner of the image to be drawn on the canvas (the destination image)</li>
<li><tt>dy</tt> is the y coordinate of the upper left corner of the destination image</li>
<li><tt>dw</tt> is the width of the destination image (optional)</li>
<li><tt>dh</tt> is the height of the destination image (optional)</li>
</ul>
<p>If <tt>dw</tt> and <tt>dh</tt> are not specified, the image retains its source dimensions when drawn on the canvas. When <tt>dw</tt> and <tt>dh</tt> are specified, the image is scaled to width <tt>dw</tt> and height <tt>dh</tt> when drawn on the canvas.</p>
<p>If you want to crop the source image, the <tt>drawImage</tt> method can be overloaded with the following arguments:</p>
<pre class="cpp"> context<span class="operator">.</span>drawImage(image<span class="operator">,</span> sx<span class="operator">,</span> sy<span class="operator">,</span> sw<span class="operator">,</span> sh<span class="operator">,</span> dx<span class="operator">,</span> dy<span class="operator">,</span> dw<span class="operator">,</span> dh)</pre>
<p>where:</p>
<ul>
<li><tt>sx</tt> is the x coordinate of the upper left corner of the cropped source image</li>
<li><tt>sy</tt> is the y coordinate of the upper left corner of the cropped source image</li>
<li><tt>sw</tt> is the width of the cropped source image</li>
<li><tt>sh</tt> is the height of the cropped source image</li>
</ul>
<p>Use this method if you want to crop the source image to the rectangle (sx, sy, sw, sh) before drawing it on the canvas. The destination image will have width <tt>dw</tt>, height <tt>dh</tt>, and upper left corner at coordinates <tt>(dx,dy)</tt> on the canvas.</p>
<p>To create a new image using JavaScript, create an <tt>Image</tt> object and define its source. Use an <tt>onload</tt> event handler to ensure that the <tt>drawImage</tt> method is not called until the image has finished loading. For example:</p>
<pre class="cpp"> var graphic <span class="operator">=</span> <span class="keyword">new</span> Image();
 graphic<span class="operator">.</span>src <span class="operator">=</span> <span class="string">&quot;clipart/graphic.png&quot;</span>;</pre>
<p>The image begins to load.</p>
<pre class="cpp"> graphic<span class="operator">.</span>onload <span class="operator">=</span> function(){
     context<span class="operator">.</span>drawImage(graphic<span class="operator">,</span>x<span class="operator">,</span>y);
 };</pre>
<a name="creating-patterns-with-images"></a>
<h3>Creating Patterns with Images</h3>
<p>You can create patterns with an image by repeating it horizontally, vertically, or both. The top left corner of the first image must be anchored at the origin of the coordinate space. To repeat an image, call the <tt>createPattern</tt> method:</p>
<pre class="cpp">     context<span class="operator">.</span>createPattern(image<span class="operator">,</span> repetition);</pre>
<p>where:</p>
<ul>
<li><tt>image</tt> is a reference to an HTML <tt>&lt;image&gt;</tt> or <tt>&lt;canvas&gt;</tt>element that is repeated to form a pattern. The image must be fully loaded before you can draw it on the canvas. The reference cannot be a URL. Instead, it should be referenced via standard DOM methods such as<ul>
<li><tt>document.images</tt> and</li>
<li><tt>document.getElementById</tt>. For example:<pre class="cpp">         <span class="operator">&lt;</span>canvas id<span class="operator">=</span><span class="string">&quot;demo1&quot;</span> width<span class="operator">=</span><span class="string">&quot;100&quot;</span> height<span class="operator">=</span><span class="string">&quot;150&quot;</span><span class="operator">&gt;</span><span class="operator">&lt;</span><span class="operator">/</span>canvas<span class="operator">&gt;</span>

         var canvas <span class="operator">=</span> document<span class="operator">.</span>getElementById(<span class="string">&quot;demo1&quot;</span>);
         var context <span class="operator">=</span> canvas<span class="operator">.</span>getContext(<span class="string">&quot;2d&quot;</span>);</pre>
</li>
</ul>
</li>
<li><tt>repetition</tt> is the direction in which the image repeats to form the pattern. Possible values are:<ul>
<li><tt>repeat</tt> (default) the image repeats both horizontally and vertically</li>
<li><tt>repeat-x</tt> the image repeats horizontally</li>
<li><tt>repeat-y</tt> the image repeats vertically</li>
</ul>
</li>
</ul>
<p>The repeated images are the same size as the source image. The <tt>createPattern</tt> method does not scale the images.</p>
<p>For example, to create a horizontal pattern of roses, create an <tt>Image</tt> object to use as a pattern and define its source. Use an <tt>onload</tt> event handler to ensure that the <tt>createPattern</tt> method is not called until the image has finished loading. For example:</p>
<pre class="cpp">     var roses <span class="operator">=</span> <span class="keyword">new</span> Image();
     roses<span class="operator">.</span>src <span class="operator">=</span> <span class="string">&quot;clipart/roses.jpg&quot;</span>;</pre>
<p>The image begins to load.</p>
<pre class="cpp">     roses<span class="operator">.</span>onload <span class="operator">=</span> function(){
         var pattern <span class="operator">=</span> context<span class="operator">.</span>createPattern(roses<span class="operator">,</span>repeat<span class="operator">-</span>x);
     };</pre>
<p class="centerAlign"><img src="images/canvas_pattern.png" alt="" /></p><a name="applying-colors"></a>
<h2>Applying Colors</h2>
<p>To draw the outline of a shape in color, set the <tt>strokeStyle</tt> attribute to any valid <a href="http://www.w3schools.com/css/css_colors.asp">CSS color value</a>. The color value can be in hexadecimal notation or in RGB/HSL notation, as described in <a href="qtwebkit-guide-css.html#specifying-color-and-opacity">Specifying Color and Opacity</a>. For example, either of the following sets a shape's outline to red:</p>
<pre class="cpp"> context<span class="operator">.</span>strokeStyle <span class="operator">=</span> <span class="string">&quot;#FF0000&quot;</span>
 context<span class="operator">.</span>strokeStyle <span class="operator">=</span> <span class="string">&quot;rgb(255,0,0)&quot;</span></pre>
<p>To fill a shape with color, set the <tt>fillStyle</tt> attribute to a l{CSS Color Value}{CSS color value}. The color value can be in hexadecimal notation or in RGB/HSL notation. For example, either of the following colors a shape's interior as blue:</p>
<pre class="cpp"> context<span class="operator">.</span>fillStyle <span class="operator">=</span> <span class="string">&quot;#0000FF&quot;</span>
 context<span class="operator">.</span>fillStyle <span class="operator">=</span> <span class="string">&quot;rgb(0,0,255)&quot;</span></pre>
<p>The <a href="http://www.w3.org/TR/2003/CR-css3-color-20030514/#numerical">CSS3 Color Module specification</a> extends both RGB and HSL color models to include a color's opacity, referred to as its <i>alpha</i>. These extended models are known as RGBA and HSLA. There are no hexadecimal notations for RGBA and HSLA values. The following specifies varying levels of opacity for a blue shape:</p>
<pre class="cpp"> context<span class="operator">.</span>fillStyle <span class="operator">=</span> rgba(<span class="number">0</span><span class="operator">,</span> <span class="number">0</span><span class="operator">,</span> <span class="number">255</span><span class="operator">,</span> <span class="number">0</span>)        <span class="comment">// transparent</span>
 context<span class="operator">.</span>fillStyle <span class="operator">=</span> rgba(<span class="number">0</span><span class="operator">,</span> <span class="number">0</span><span class="operator">,</span> <span class="number">255</span><span class="operator">,</span> <span class="number">0.5</span>)    <span class="comment">// semi-transparent</span>
 context<span class="operator">.</span>fillStyle <span class="operator">=</span> rgba(<span class="number">0</span><span class="operator">,</span> <span class="number">0</span><span class="operator">,</span> <span class="number">255</span><span class="operator">,</span> <span class="number">1</span>)        <span class="comment">// opaque</span></pre>
<p>When you set the <tt>context.strokeStyle</tt> or <tt>context.fillStyle</tt> attributes, whatever value you set becomes the default value for all subsequently drawn shapes, until you set a new value.</p>
<a name="applying-gradients"></a>
<h3>Applying Gradients</h3>
<p>A gradient is a smooth transition between colors. There are two types of gradients: linear and radial.</p>
<p>A linear gradient transitions the color along a line between two points. To create a linear gradient, call the <tt>createLinearGradient</tt> method:</p>
<pre class="cpp">     createLinearGradient(x0<span class="operator">,</span> y0<span class="operator">,</span> x1<span class="operator">,</span> y1)</pre>
<p>where <tt>(x0, y0)</tt> is the starting point and <tt>(x1, y1)</tt> is the ending point for the linear gradient.</p>
<p>A radial gradient transitions the color along a cone between two circles. To create a radial gradient, call the <tt>createRadialGradient</tt> method:</p>
<pre class="cpp">     createRadialGradient(x0<span class="operator">,</span> y0<span class="operator">,</span> r0<span class="operator">,</span> x1<span class="operator">,</span> y1<span class="operator">,</span> r1)</pre>
<p>where:</p>
<ul>
<li><tt>(x0, y0, r0)</tt> represents the starting circle, whose origin is <tt>(x0, y0)</tt> and whose radius is <tt>r0</tt>.</li>
<li><tt>(x1, y1, r1)</tt> represents the ending circle, whose origin is <tt>(x1, y1)</tt> and whose radius is <tt>r1</tt>.</li>
</ul>
<p>Gradients must have two or more <i>color stops</i>, representing color shifts positioned from <tt>0</tt> to <tt>1</tt> between to the gradient's starting and end points or circles:</p>
<pre class="cpp">     addColorStop(position<span class="operator">,</span>color)</pre>
<p>where:</p>
<ul>
<li><tt>position</tt> specifies the position of the color within the already defined starting and end points or circles, expressed as a number from <tt>0</tt> to <tt>1</tt>.</li>
<li><tt>color</tt> specifies the CSS color at that position.</li>
</ul>
<p>For example, to define a gradient that varies from red to blue horizontally along a rectangular area:</p>
<ol class="1">
<li>Create a gradient object:<pre class="cpp">         var redbluegradient <span class="operator">=</span> context<span class="operator">.</span>createLinearGradient(<span class="number">0</span><span class="operator">,</span><span class="number">0</span><span class="operator">,</span><span class="number">100</span><span class="operator">,</span><span class="number">0</span>);</pre>
</li>
<li>Define the color stops:<pre class="cpp">         redbluegradient<span class="operator">.</span>addColorStop(<span class="number">0</span><span class="operator">,</span> <span class="string">&quot;rgb(255,0,0)&quot;</span>); <span class="comment">// red at the left side of the rectangle</span>
         redbluegradient<span class="operator">.</span>addColorStop(<span class="number">1</span><span class="operator">,</span> <span class="string">&quot;rgb(0,0,255)&quot;</span>); <span class="comment">// blue at the right side of the rectangle</span></pre>
</li>
<li>Draw the shape and set a <tt>fillStyle</tt> or <tt>strokeStyle</tt>:<pre class="cpp">         context<span class="operator">.</span>fillStyle <span class="operator">=</span> redbluegradient;
         context<span class="operator">.</span>fillRect(<span class="number">0</span><span class="operator">,</span><span class="number">0</span><span class="operator">,</span><span class="number">100</span><span class="operator">,</span><span class="number">150</span>);</pre>
</li>
</ol>
<p>To define a gradient that varies from red to blue vertically along a rectangle:</p>
<ol class="1">
<li>Create a gradient object:<pre class="cpp">     var redbluegradient <span class="operator">=</span> context<span class="operator">.</span>createLinearGradient(<span class="number">0</span><span class="operator">,</span><span class="number">0</span><span class="operator">,</span><span class="number">0</span><span class="operator">,</span><span class="number">150</span>);</pre>
</li>
<li>Define the color stops:<pre class="cpp">     redbluegradient<span class="operator">.</span>addColorStop(<span class="number">0</span><span class="operator">,</span> <span class="string">&quot;rgb(255,0,0)&quot;</span>); <span class="comment">// red at the top of the rectangle</span>
     redbluegradient<span class="operator">.</span>addColorStop(<span class="number">1</span><span class="operator">,</span> <span class="string">&quot;rgb(0,0,255)&quot;</span>); <span class="comment">// blue at the bottom of the rectangle</span></pre>
</li>
<li>Draw the shape and set a <tt>fillStyle</tt> or <tt>strokeStyle</tt>:<pre class="cpp">     context<span class="operator">.</span>fillStyle <span class="operator">=</span> redbluegradient;
     context<span class="operator">.</span>fillRect(<span class="number">0</span><span class="operator">,</span><span class="number">0</span><span class="operator">,</span><span class="number">100</span><span class="operator">,</span><span class="number">150</span>);</pre>
</li>
</ol>
<p><b>Note:</b> A canvas gradient's color stops behave slightly differently than those used within non-canvas <a href="demos-gradients.html">gradients</a>. Webkit gradients specify mandatory <tt>from</tt> and <tt>to</tt> colors, with optional <tt>color-stop</tt> values for additional color shifts within the overall range of the gradient. For canvas gradients, even the initial and final colors are defined as color stops.</p>
<a name="applying-shadows"></a>
<h3>Applying Shadows</h3>
<p>To add a shadow effect to a drawing on a canvas, set the following attributes:</p>
<ul>
<li><tt>shadowColor</tt> sets the color of the shadow. The value can be any CSS color value. The default value is transparent black (<tt>&quot;rgba(0,0,0,0)&quot;</tt>).</li>
<li><tt>shadowBlur</tt> sets the amount of blur in the shadow, in pixels. The value can be any positive number or 0. A value of 0 produces a sharp shadow with no blur.</li>
<li><tt>shadowOffsetX</tt> sets the number of pixels the shadow extends horizontally from the object drawn. If this value is a positive number, the shadow extends to the right of the object. If negative, the shadow extends to the left of the object. The default value is 0 pixels.</li>
<li><tt>shadowOffsetY</tt> sets the number of pixels the shadow extends vertically from the object drawn. If this value is a positive number, the shadow extends below the object. If negative, the shadow extends above the object. The default value is 0 pixels.</li>
</ul>
<p>The following example code adds a semi-transparent black shadow to the bottom right of a blue rectangle:</p>
<pre class="cpp">     var context        <span class="operator">=</span> canvas<span class="operator">.</span>getContext(<span class="string">&quot;2d&quot;</span>);
     context<span class="operator">.</span>shadowOffsetX    <span class="operator">=</span> <span class="number">5</span>;
     context<span class="operator">.</span>shadowOffsetY    <span class="operator">=</span> <span class="number">5</span>;
     context<span class="operator">.</span>shadowBlur    <span class="operator">=</span> <span class="number">10</span>;
     context<span class="operator">.</span>shadowColor    <span class="operator">=</span> <span class="string">&quot;rgba(0,0,0,0.5)&quot;</span>;
     context<span class="operator">.</span>fillStyle    <span class="operator">=</span> <span class="string">&quot;#0000FF&quot;</span>;
     context<span class="operator">.</span>fillRect    <span class="operator">=</span> (<span class="number">0</span><span class="operator">,</span><span class="number">0</span><span class="operator">,</span><span class="number">100</span><span class="operator">,</span><span class="number">50</span>)</pre>
<a name="transforming-graphics"></a>
<h2>Transforming Graphics</h2>
<p>When drawing shapes and paths, you can translate the canvas's origin, rotate the canvas around the origin, scale the units in the canvas grid, and modify the transformation matrix directly.</p>
<a name="translating-the-canvas-origin"></a>
<h3>Translating the Canvas Origin</h3>
<p>Translating the origin enables you to draw patterns of different objects on the canvas without having to measure the coordinates manually for each shape. To translate the origin of the canvas, use the <tt>translate</tt> method:</p>
<pre class="cpp">     context<span class="operator">.</span>translate(x<span class="operator">,</span>y);</pre>
<p>where:</p>
<ul>
<li><tt>x</tt> is the horizontal distance that the origin is translated, in coordinate space units</li>
<li><tt>y</tt> is the vertical distance that the origin is translated, in coordinate space units</li>
</ul>
<a name="rotating-the-canvas"></a>
<h3>Rotating the Canvas</h3>
<p>To rotate the canvas around the current origin, call the <tt>rotate()</tt> method:</p>
<pre class="cpp">     context<span class="operator">.</span>rotate(angle);</pre>
<p>where <tt>angle</tt> is the clockwise rotation angle in radians. The number of radians is the number of degrees multiplied by &Pi;/180, expressed in JavaScript as:</p>
<pre class="cpp">     var radians <span class="operator">=</span> (Math<span class="operator">.</span>PI<span class="operator">/</span><span class="number">180</span>)<span class="operator">*</span>degrees;</pre>
<p class="centerAlign"><img src="images/canvas_rotate.png" alt="" /></p><a name="scaling-the-canvas-grid"></a>
<h3>Scaling the Canvas Grid</h3>
<p>To increase or decrease the size of each unit in the canvas grid, call the <tt>scale</tt> method:</p>
<pre class="cpp">     context<span class="operator">.</span>scale(x<span class="operator">,</span>y);</pre>
<p>where:</p>
<ul>
<li><tt>x</tt> is the scale factor in the horizontal direction</li>
<li><tt>y</tt> is the scale factor in the vertical direction</li>
</ul>
<p>The scale factors are in multiples. For example, <tt>scale(2.0, 0.5)</tt> would double the horizontal size of an object drawn on the canvas and half its vertical size, as shown below:</p>
<p class="centerAlign"><img src="images/canvas_scale.png" alt="" /></p><a name="manipulating-the-transformation-matrix"></a>
<h3>Manipulating the Transformation Matrix</h3>
<p>Modifying the transformation matrix directly enables you to perform scaling, rotating, and translating transformations in a single step.</p>
<p>The transformation matrix is an <i>affine transformation</i> matrix from linear algebra. Affine transformations preserve colinearity and relative distance in the transformed coordinate space. This means that points in a line remain in a line, parallel lines remain parallel, and the distance between lines and objects maintains the same ratio, even if a scale factor is applied. Repositioning by translation, rotation, or skewing is also possible.</p>
<p>Each point on the canvas is multiplied by the matrix before anything is drawn. The <a href="http://dev.w3.org/html5/canvas-api/canvas-2d-api.html">HTML5 Canvas API</a> defines the transformation matrix as:</p>
<p class="centerAlign"><img src="images/canvas_math.png" alt="" /></p><p>where:</p>
<ul>
<li><tt>a</tt> is the scale factor in the horizontal (x) direction<p class="centerAlign"><img src="images/canvas_scalex.png" alt="" /></p></li>
<li><tt>c</tt> is the skew factor in the x direction<p class="centerAlign"><img src="images/canvas_skewx.png" alt="" /></p></li>
<li><tt>e</tt> is the translation in the x direction<p class="centerAlign"><img src="images/canvas_translate.png" alt="" /></p></li>
<li><tt>b</tt> is the skew factor in the y (vertical) direction<p class="centerAlign"><img src="images/canvas_skewy.png" alt="" /></p></li>
<li><tt>d</tt> is the scale factor in the y direction<p class="centerAlign"><img src="images/canvas_scaley.png" alt="" /></p></li>
<li><tt>f</tt> is the translation in the y direction<p class="centerAlign"><img src="images/canvas_translatey.png" alt="" /></p></li>
<li>the last row remains constant</li>
</ul>
<p>The scale factors and skew factors are multiples; <tt>e</tt> and <tt>f</tt> are coordinate space units, just like the units in the <tt>translate(x,y)</tt> method.</p>
<p>The rotation transformation matrix is as follows:</p>
<p class="centerAlign"><img src="images/canvas_math_rotate.png" alt="" /></p><p>where the <tt>angle</tt> of rotation is in radians.</p>
<p><b>See Also:</b> <a href="http://www.senocular.com/flash/tutorials/transformmatrix/">senocular.com</a> for a good explanation of how transformation matrices are used identically within Adobe Flash.</p>
<a name="canvas-animations"></a>
<h2>Canvas Animations</h2>
<p>You can animate a canvas drawing by repeatedly redrawing the canvas for each frame and translating, rotating, skewing, and scaling the drawn objects.</p>
<p>To draw each frame by employing the HTML5 canvas API, you should define the original canvas state and save it for future reference. The drawing context maintains a stack of drawing states. Each state consists of the current transformation matrix, current clipping region, and current values of the following attributes:</p>
<ul>
<li><tt>strokeStyle</tt></li>
<li><tt>fillStyle</tt></li>
<li><tt>globalAlpha</tt></li>
<li><tt>lineWidth</tt></li>
<li><tt>lineCap</tt></li>
<li><tt>lineJoin</tt></li>
<li><tt>miterLimit</tt></li>
<li><tt>shadowOffsetX</tt></li>
<li><tt>shadowOffsetY</tt></li>
<li><tt>shadowBlur</tt></li>
<li><tt>shadowColor</tt></li>
<li><tt>globalCompositeOperation</tt></li>
<li><tt>font</tt></li>
<li><tt>textAlign</tt></li>
<li><tt>textBaseline</tt></li>
</ul>
<p>The current path and the current bitmap are NOT part of the drawing state. The path can be reset only by invoking the <tt>beginPath()</tt> method. The current bitmap is a property of the canvas, not of the context.</p>
<p>To save the original canvas state, call the <tt>save()</tt> method:</p>
<pre class="cpp"> context<span class="operator">.</span>save();</pre>
<p>Before drawing each new frame, you must clear the canvas:</p>
<pre class="cpp"> canvas<span class="operator">.</span>clearRect(x<span class="operator">,</span>y<span class="operator">,</span>width<span class="operator">,</span>height);</pre>
<p>where:</p>
<ul>
<li><tt>x</tt> is the position of the top left corner of the canvas on the horizontal axis</li>
<li><tt>y</tt> is the position of the top left corner of the canvas on the vertical axis</li>
<li><tt>width</tt> is the width of the canvas</li>
<li><tt>height</tt> is the height of the canvas</li>
</ul>
<p>Draw the new frame using any of the methods provided by the canvas API. Then save it by calling the <tt>save()</tt> method.</p>
<p>If you wish to return to the state of the original frame as the basis for each new frame that you draw, call the <tt>context.restore()</tt> method.</p>
<p>To execute the drawing methods repeatedly, use the standard JavaScript-based animation technique, calling the <tt>setInterval()</tt> and <tt>clearInterval()</tt> methods. The following shows how to execute an animation function every <tt>50</tt> milliseconds (corresponding to 20 times per second, a typical animation frame rate), then subsequently halt the animation:</p>
<pre class="cpp"> var id <span class="operator">=</span> setInterval(functionName<span class="operator">,</span> <span class="number">50</span>);
 clearInterval(id);</pre>
<p><b>See Also:</b></p>
<ul>
<li><a href="http://www.canvasdemos.com/2009/10/09/html-5-canvas-animation/">CanvasDemos.com: animated cartoon</a>, which discusses how to use Canvas as an animation framework.</li>
<li><a href="http://blog.nihilogic.dk/2009/02/html5-canvas-cheat-sheet.html">nihilogic.dk: HTML5 Canvas Cheat Sheet</a></li>
<li><a href="qtwebkit-guide.html">QtWebKit Guide</a> -back to the main page</li>
</ul>
</div>
<!-- @@@qtwebkit-guide-canvas.html -->
      </div>
    </div>
    </div> 
    <div class="ft">
      <span></span>
    </div>
  </div> 
  <div class="footer">
    <p>
      <acronym title="Copyright">&copy;</acronym> 2013 Digia Plc and/or its
      subsidiaries. Documentation contributions included herein are the copyrights of
      their respective owners.</p>
    <br />
    <p>
      The documentation provided herein is licensed under the terms of the
      <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation
      License version 1.3</a> as published by the Free Software Foundation.</p>
    <p>
      Documentation sources may be obtained from <a href="http://www.qt-project.org">
      www.qt-project.org</a>.</p>
    <br />
    <p>
      Digia, Qt and their respective logos are trademarks of Digia Plc 
      in Finland and/or other countries worldwide. All other trademarks are property
      of their respective owners. <a title="Privacy Policy"
      href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p>
  </div>

  <script src="scripts/functions.js" type="text/javascript"></script>
</body>
</html>