HTML5 canvas tutorial for beginners - getContext() toDataURL() toBlob()

The canvas element is part of HTML5 that allows for dynamic rendering of 2D shapes and bitmap images. With the help of HTML5 Canvas you can draw lines, curves, shapes, gradients, patterns, images, text, etc. Not all browsers currently support canvas element so if you define a canvas element and the browser doesn't support it will just display the text inside the tags instead of drawing the canvas on the page.

HTML5 canvas tutorial for beginners
Canvas consists of a drawable region defined in HTML code with height and width attributes. The example below uses the ExtJs JavaScript framework to draw a line, an arc, a rectangle and some Text inside the canvas element.


HTML5 canvas tutorial for beginners

Basically when the page has been rendered the ExtJs launch function is called very similar to the window.onload function after the page loads. Now that we know that canvas has been rendered on the page we get reference to the canvas DOM object by its id using the getElementById method, and then get a 2d context using the getContext() method.

Source for the HTML file - myCanvas.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>HTML 5 canvas Tutorial</title>
<link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css">
<style type="text/css">
    body {
        margin: 10px 10px 10px 10px;
    }
</style>
<script type="text/javascript" src="extjs/ext-all-debug.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>

    <b>HTML 5 canvas Tutorial</b> 
    <br></br> 
    <canvas id="myCanvas" width="500" height="250"
        style="border:1px solid #c3c3c3;"> 
        Your browser does not support the HTML 5 canvas element! 
    </canvas>
   
</body>
</html>

Source for the Javascript file - app.js

Ext.Loader.setConfig({ 
    enabled: true 
});

Ext.application({
   
    name: 'HTML5Canvas',
    appFolder: 'app',
   
    launch: function() {
        var myCanvasElement = document.getElementById("myCanvas");
        var context = myCanvasElement.getContext("2d");
       
        //draw a line
        context.beginPath();
        context.moveTo(20,20);
        context.lineTo(220,20);
        context.lineWidth = 3;
        context.stroke();
       
        // draw an arc
        context.beginPath();
        context.arc(120, 100, 50, 1*Math.PI , 2*Math.PI ,false);
        context.lineWidth = 3;
        context.stroke();
       
        //draw a rectangle
        context.beginPath();
        context.rect(20, 150, 200, 50);
        context.lineWidth = 3;
        context.stroke();
       
        //draw some text
        context.beginPath();
        context.font="26px Arial";
        context.fillText("HTML5 Canvas",300,50); 
        context.lineWidth = 3;
        context.stroke();
       
    }
});

The getContext("2d") object has methods to draw lines, rectangles , circles, etc. In addition to the getContext() method we have 2 other methods toDataURL() and toBlob(). Both methods help us save the contents of the canvas so we can use them later.

Please Note: The x,y coordinate 0,0 is the Top Left corner of the canvas!

toDataURL(in optional DOMString type, in any... args)


Returns a data: URL for the image in the canvas
The first argument, if provided, controls the type of the image to be returned (e.g. PNG or JPEG). The default is image/png; that type is also used if the given type isn't supported.When trying to use types other than "image/png", authors can check if the image was really returned in the requested format by checking to see if the returned string starts with one of the exact strings "data:image/png," or "data:image/png;". If it does, the image is PNG, and thus the requested type was not supported.
The one exception to this is if the canvas has either no height or no width, in which case the result might simply be "data:,".

Example:
function saveImage() {
    var canvas = document.getElementById("MyCanvas");       
          if (canvas.getContext) {
            // Get the context for the canvas
             var ctx = canvas.getContext("2d"); 
            // Get the data as an image.             
             var myImage = canvas.toDataURL("image/png");     
          }
  
    // Get the img object
    var imageElement = document.getElementById("MyPix");
    // Set the src to data from the canvas 
    imageElement.src = myImage;                          
}

toBlob(in FileCallback, in optional DOMString type, in any... args)


Creates a Blob object representing a file containing the image in the canvas, and invokes a callback with a handle to that object.The second argument, if provided, controls the type of the image to be returned (e.g. PNG or JPEG). The default is image/png; that type is also used if the given type isn't supported.

Example:
function saveImage() {
    var canvas = document.getElementById("canvas"); 
    canvas.toBlob(function(blob) { 
        var newImg = document.createElement("img"), 
        url = URL.createObjectURL(blob); 
        newImg.onload = function() { 
            // no longer need to read the blob so it's revoked 
            URL.revokeObjectURL(url); 
        }; 
        newImg.src = url; 
        document.body.appendChild(newImg); 
    });                           
}

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.