HTML5 Canvas

< Overview | Canvas | Forms Elements Local Storage   |  >
HTML5 Powered

Canvas

A canvas is an area where we can draw text, lines, shapes and other things. The upper left corner has the coordinates of (0,0) with the values increasing going to the right and down.

  1. Square

    Let's draw a red square inside a canvas. Here's the code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title>Example of Drawing a Rectangle in HTML5</title>
     <style type="text/css">
         canvas {border-width: 1; border: solid; text-align: center}
     </style>
    <script type="text/javascript">
            window.onload=draw;
            function draw() {
               var mycanvas = document.getElementById("mycanvas");
               var context = mycanvas.getContext("2d");
               context.fillStyle = "#f00";
               context.fillRect(200, 50, 20, 40); // (x,y,width,height)
            }
    </script>
    </head>
    <body>
    <h1>Example of Drawing a Rectangle in HTML5</h1>
    <canvas id="mycanvas" width="350" height="350">
    <p>Unfortunately your browser does not support the "canvas" element.  
    Please upgrade to a new version of a browser like 
    <a href="http://www.mozilla.org/en-US/products/download.html">Firefox</a>.</p>
    </canvas>
    </body>
    </html>
    

    Click here to see the page in living color.

    You should not use the xml shorthand to close a canvas element (ie, <canvas ... /> instead of <canvas ...> ... </canvas> ) alway use an end tag and in between them include fallback content or a message for browsers that do not support the canvas element.

  2. Lines

    Let's draw a red line. Here's the code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="robots" content="noindex">
    <title>Example of Drawing Shapes in HTML5</title>
     <style type="text/css">
         canvas {border-width: 1; border: solid; text-align: center}
     </style>
     <script type="text/javascript">
    window.onload=draw;
    function draw() {
       var mycanvas = document.getElementById("mycanvas");
       var context = mycanvas.getContext("2d");
       context.beginPath(); 
         context.moveTo(10, 10);
         context.lineTo(200, 200);
         context.lineTo(200, 10);
         context.lineTo(10, 10);
         context.strokeStyle = "#0e0";
       context.closePath(); 
       context.stroke(); //nothing is drawn until "stroke()" is executed.
    
       context.beginPath(); 
         context.moveTo(50, 100);
         context.lineTo(250, 300);
         context.lineTo(250, 100);
         context.lineTo(50, 100);
         context.fillStyle = "rgba(255,0,0,0.2)"; //"#f00";
       context.closePath(); //when calling "fill" closePath() is optional
       context.fill(); 
    
       context.beginPath(); 
         //arc(x,y,radius,startAngle,endAngle, anticlockwise); //angles in radians, anticlockwise is boolean
         context.arc(200, 200, 100, 0, Math.PI*2.0, false);
         context.fillStyle = "rgba(0,0,200,0.2)"; //"#f00";
       context.closePath(); //when calling "fill" closePath() is optional
       context.fill(); 
    
    
    
    }
     </script>
    </head>
    <body>
    <h1>Example of Drawing Shapes in HTML5</h1>
    <canvas id="mycanvas" width="350" height="350"></canvas>
    </body>
    </html>
    

    Click here to see the page.

    To make it more interesting we can create a spirograph type design:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title>Example of Drawing Lines in HTML5</title>
     <style type="text/css">
         canvas {border-width: 1; border: solid; text-align: center}
     </style>
     <script type="text/javascript">
    window.onload=draw;
    function draw() {
       var mycanvas = document.getElementById("mycanvas");
       var context = mycanvas.getContext("2d");
       var numberOfPoints = 25;
       var angleInRadians = 2.0 * Math.PI / numberOfPoints;
       var canvasWidth = 500;
       var radius = (canvasWidth - 100)/2;
       var x = new Array();
       var y = new Array();
       for(var i=0; i < numberOfPoints; i++) {
            x[i] = Math.cos(i*angleInRadians) * radius + canvasWidth/2;
            y[i] = Math.sin(i*angleInRadians) * radius + canvasWidth/2;
       }
    
       for(var i=0; i < numberOfPoints; i++) {
         for(var j=0; j < numberOfPoints; j++) {
            context.moveTo(x[i],y[i]);
            context.lineTo(x[j], y[j]);
         }
       }
       context.strokeStyle = "#0e0";
       context.stroke(); //nothing is drawn until "stroke()" is executed.
    }
     </script>
    </head>
    <body>
    <h1>Example of Drawing Lines in HTML5</h1>
    <canvas id="mycanvas" width="500" height="500"></canvas>
    </body>
    </html>
    

    Click here to see the page.

  3. Text

    Let's draw some text. Here's the code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title>Example of Drawing Text in HTML5</title>
     <style type="text/css">
         canvas {border-width: 1; border: solid; text-align: center}
     </style>
    <script type="text/javascript">
    window.onload=draw;
    function draw() {
       var mycanvas = document.getElementById("mycanvas");
       var context = mycanvas.getContext("2d");
       context.fillStyle = "#f00";
       context.font = "bold 12px sans-serif";
       context.textAlign = "center"; // or "left", "right", "start", "end"
       context.textBaseline = "middle"; // "top", "middle", "bottom" ...
       context.fillText("Hello World!", 150, 150);
    }
    </script>
    </head>
    <body>
    <h1>Example of Drawing Text in HTML5</h1>
    <canvas id="mycanvas" width="300" height="300"></canvas>
    </body>
    </html>
    

    Click here to see the page.

  4. Gradient

    Let's do a gradient. Here's the code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title>Example of Drawing a Gradient in HTML5</title>
     <style type="text/css">
         canvas {border-width: 1; border: solid; text-align: center}
     </style>
    <script type="text/javascript">
            window.onload=draw;
            function draw() {
               var mycanvas = document.getElementById("mycanvas");
               var context = mycanvas.getContext("2d");
    	   var gradient = context.createLinearGradient(50, 50, 200, 0);//horz gradient
    	   gradient.addColorStop(0, "green");
    	   gradient.addColorStop(1, "white");
               context.fillStyle = gradient;
               context.fillRect(50, 50, 200, 100); // (x,y,width,height)
    
    	   var gradient2 = context.createLinearGradient(50, 200, 50, 300);//vert gradient
    	   gradient2.addColorStop(0, "red");
    	   gradient2.addColorStop(1, "white");
               context.fillStyle = gradient2;
               context.fillRect(50, 200, 200, 100); // (x,y,width,height)
            }
    </script>
    </head>
    <body>
    <h1>Example of Drawing a Gradient in HTML5</h1>
    <canvas id="mycanvas" width="350" height="350"></canvas>
    </body>
    </html>
    

    Click here to see the page.

  5. Reading mouse clicks

    Let's read a mouse click, not really a part of HTML5, but useful. Here's the code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title>Example of Handling Mouse Clicks in HTML5</title>
     <style type="text/css">
         canvas {border-width: 1; border: solid; text-align: center}
     </style>
    <script type="text/javascript">
    window.onload=init;
    function mouseClick(e) {
       var mycanvas = document.getElementById("mycanvas");
       var context = mycanvas.getContext("2d");
       var point = getMousePoint(mycanvas, e);
       context.fillStyle = "#f00";
       context.font = "bold 12px sans-serif";
       context.textAlign = "center"; // or "left", "right", "start", "end"
       context.textBaseline = "middle"; // "top", "middle", "bottom" ...
       context.fillText("("+point.x+","+point.y+")", point.x,point.y);
    }
    function getMousePoint(mycanvas, e) {
       var x;
       var y;
       if (e.pageX || e.pageY) { 
         x = e.pageX;
         y = e.pageY;
       }
       else { 
         x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 
         y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
       } 
       x -= mycanvas.offsetLeft;
       y -= mycanvas.offsetTop;
       mypoint = new Object();
       mypoint.x = x;
       mypoint.y = y;
       return mypoint;
    }
    function init() {
       var mycanvas = document.getElementById("mycanvas");
       var context = mycanvas.getContext("2d");
       mycanvas.addEventListener("click", mouseClick, false);
    }
    </script>
    </head>
    <body>
    <h1>Example of Handling Mouse Clicks in HTML5</h1>
    <canvas id="mycanvas" width="300" height="300"></canvas>
    </body>
    </html>
    

    Click here to see the page.

  6. Following the mouse

    Here's the code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title>Example of Following the Mouse</title>
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
      <script>window.jQuery || document.write('<script src="js/libs/jquery-1.6.2.min.js"><\/script>')</script>
     <style type="text/css">
         canvas {border-width: 1; border: solid; text-align: center}
     </style>
    <script type="text/javascript">
    var width=800;
    var height=600;
    window.onload=init;
    function mouseMove(e) {
       var mycanvas = document.getElementById("mycanvas");
       var context = mycanvas.getContext("2d");
       var point = getMousePoint(mycanvas, e);
       
       red = Math.floor(16*(point.y+point.x)/2/width).toString(16);
       green = Math.floor(16*point.y/height).toString(16);
       blue = Math.floor(16*point.x/width).toString(16);
       context.fillStyle = "#"+red+green+blue;
       clearScreen();
       context.beginPath();
          context.arc(point.x,point.y,10,0, Math.PI*2,true);
       context.fill();
       context.fillText("    color:"+context.fillStyle, point.x,point.y);
    }
    function clearScreen() {
       var mycanvas = document.getElementById("mycanvas");
       var context = mycanvas.getContext("2d");
       context.clearRect(0,0,width,height);
    }
    function getMousePoint(mycanvas, e) {
       var x;
       var y;
       if (e.pageX || e.pageY) { 
         x = e.pageX;
         y = e.pageY;
       }
       else { 
         x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 
         y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
       } 
       x -= mycanvas.offsetLeft;
       y -= mycanvas.offsetTop;
       mypoint = new Object();
       mypoint.x = x;
       mypoint.y = y;
       return mypoint;
    }
    function init() {
       $('#mycanvas').bind("mousemove", mouseMove);
       $('#mycanvas').bind("mouseleave", clearScreen);
    }
    </script>
    </head>
    <body>
    <h1>Example of Following the Mouse</h1>
    <canvas id="mycanvas" width=800 height=600></canvas>
    </body>
    </html>
    

    Click here to see the page.

  7. Drawing a Pattern

    Here's the code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title>Doodle Dot</title>
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
      <script>window.jQuery || document.write('<script src="js/libs/jquery-1.6.2.min.js"><\/script>')</script>
     <style type="text/css">
         canvas {border-width: 1; border: solid; text-align: center}
     </style>
    <script type="text/javascript">
    var context;
    var width=800;
    var height=600;
    var radius=10;
    var dx=3;
    var dy=3;
    var x=100;
    var y=100;
    var color = "#ff0000";
    var intervalId;
    var counter = 0;
    var counterMax = 20000;
    
    window.onload=init;
    function init() {
       var mycanvas = document.getElementById("mycanvas");
       context = mycanvas.getContext("2d");
       $('#mycanvas').bind("click", mouseClick);
    }
    function mouseClick(e) {
       var mycanvas = document.getElementById("mycanvas");
       var point = getMousePoint(mycanvas, e);
       x = point.x;
       y = point.y;
       color = getColorFromPoint(x,y);
       reset();
       intervalId = setInterval(drawBall,10);
    }
    function getColorFromPoint(x,y) {
       red = Math.floor(16*(y+x)/2/width);
       green = Math.floor(16*y/height);
       blue = Math.floor(16*x/width);
       color = "rgba("+red*16+","+green*16+","+blue*16+", 0.2)";
       //color = "#"+red.toString(16)+green.toString(16)+blue.toString(16);
       return color;
    }
    function drawBall() {
      // clearScreen(); //uncomment this to get bouncing ball
       context.beginPath();
       context.fillStyle = color;
       context.arc(x,y,2*radius,0, Math.PI*2,true);
       context.closePath();
       context.fill();
       if( x-radius<0 || x+radius>width) { dx=-dx; y++; }
       if( y-radius<0 || y+radius>height) { dy=-dy; x++; }
       x+=dx;
       y+=dy;
       counter++;
       if(counter%5 == 0)$('#counter').html(counter);
       if(counter>counterMax) {
          reset();
       }
    }
    function reset() {
        counter = 0;
        clearInterval(intervalId);
    }
    
    function clearScreen() {
    reset();
       context.clearRect(0,0,width,height);
    }
    function save() {
    reset();
    alert('I will forward you to a new tab/window with your image.  Right click and select "Save image as...".  Then delete the tab/window.');
       var mycanvas = document.getElementById("mycanvas");
       window.open(mycanvas.toDataURL("image/png"),'_blank');
    }
    function getMousePoint(mycanvas, e) {
       var x;
       var y;
       if (e.pageX || e.pageY) { 
         x = e.pageX;
         y = e.pageY;
       }
       else { 
         x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 
         y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
       } 
       x -= mycanvas.offsetLeft;
       y -= mycanvas.offsetTop;
       mypoint = new Object();
       mypoint.x = x;
       mypoint.y = y;
       return mypoint;
    }
    </script>
    </head>
    <body>
    
    <h1>Doodle Dot</h1>
    <p>Clicking in different spots makes different colors.</p>
    <canvas id="mycanvas" width=800 height=600></canvas>
    <p>
    <input type="button" value="Stop" id="Stop" />
    <input type="button" value="Clear" id="Clear" />
    <input type="button" value="Save" id="Save" />
    <span id="counter">0</span>
    </p>
    <script>
    $('#Stop').bind('click',function(){reset();});
    $('#Clear').bind('click',function(){clearScreen();});
    $('#Save').bind('click',function(){save();});
    </script>
    </body>
    </html>
    

    Click here to see the page.

A good cheat sheet for the canvas object is here.

Misc Notes:

context.save(); //pushes a checkpoint of the graphics state 
context.restore(); //pops checkpoint back into use
context.translate(x,y); //moves the origin to this point
context.fillRect(x,y,width,height) // Draws a filled rectangle
context.strokeRect(x,y,width,height) // Draws only the outline
context.clearRect(x,y,width,height) // Clears the rect and makes it transparent

< Overview | Canvas | Forms Elements Local Storage   |  >