Analog Clock HTML5 Canvas

Following listing shows Analog Clock in HTML 5, Tested with Mozilla, Chrome and Safari

Example

<!DOCTYPE HTML>
<html>
    <head>
        <title>Canvas tutorial</title>
        <script>
            function init(){
                clock();
                setInterval(clock, 1000);
            }

            function clock(){
                var now = new Date();
                var ctx = document.getElementById('canvas').getContext('2d');
                ctx.save();
                ctx.clearRect(0, 0, 150, 150);
                ctx.translate(75, 75);
                ctx.scale(0.4, 0.4);
                ctx.rotate(-Math.PI / 2);
                ctx.strokeStyle = "black";
                ctx.fillStyle = "white";
                ctx.lineWidth = 8;
                ctx.lineCap = "round";

                // Hour marks
                ctx.save();
                for (var i = 0; i < 12; i++) {
                    ctx.beginPath();
                    ctx.rotate(Math.PI / 6);
                    ctx.moveTo(100, 0);
                    ctx.lineTo(120, 0);
                    ctx.stroke();
                }
                ctx.restore();

                // Minute marks
                ctx.save();
                ctx.lineWidth = 5;
                for (i = 0; i < 60; i++) {
                    if (i % 5 != 0) {
                        ctx.beginPath();
                        ctx.moveTo(117, 0);
                        ctx.lineTo(120, 0);
                        ctx.stroke();
                    }
                    ctx.rotate(Math.PI / 30);
                }
                ctx.restore();

                var sec = now.getSeconds();
                var min = now.getMinutes();
                var hr = now.getHours();
                hr = hr >= 12 ? hr - 12 : hr;

                ctx.fillStyle = "black";

                // write Hours
                ctx.save();
                ctx.rotate(hr * (Math.PI / 6) + (Math.PI / 360) *
                min + (Math.PI / 21600) * sec)
                ctx.lineWidth = 14;
                ctx.beginPath();
                ctx.moveTo(-20, 0);
                ctx.lineTo(80, 0);
                ctx.stroke();
                ctx.restore();

                // write Minutes
                ctx.save();
                ctx.rotate((Math.PI / 30) * min + (Math.PI / 1800) * sec)
                ctx.lineWidth = 10;
                ctx.beginPath();
                ctx.moveTo(-28, 0);
                ctx.lineTo(112, 0);
                ctx.stroke();
                ctx.restore();

                // Write seconds
                ctx.save();
                ctx.rotate(sec * Math.PI / 30);
                ctx.strokeStyle = "#D40000";
                ctx.fillStyle = "#D40000";
                ctx.lineWidth = 6;
                ctx.beginPath();
                ctx.moveTo(-30, 0);
                ctx.lineTo(83, 0);
                ctx.stroke();
                ctx.beginPath();
                ctx.arc(0, 0, 10, 0, Math.PI * 2, true);
                ctx.fill();
                ctx.beginPath();
                ctx.arc(95, 0, 10, 0, Math.PI * 2, true);
                ctx.stroke();
                ctx.fillStyle = "rgba(0,0,0,0)";
                ctx.arc(0, 0, 3, 0, Math.PI * 2, true);
                ctx.fill();
                ctx.restore();

                ctx.beginPath();
                ctx.lineWidth = 14;
                ctx.strokeStyle = '#325FA2';
                ctx.arc(0, 0, 142, 0, Math.PI * 2, true);
                ctx.stroke();

                ctx.restore();
            }
        </script>
    </head>
    <body onload="init();">
        <canvas id="canvas" width="200" height="200">
        </canvas>
    </body>
</html>

Output

Untitled

Clipping paths

A clipping path is like a normal canvas shape but it acts as a mask to hide unwanted parts of shapes.
 
We use the clip method to create a new clipping path. By default the canvas element has a clipping path that’s the exact same size as the canvas itself (i.e. no clipping occurs).
 
In below example We’ll be using a circular clipping path to restrict the drawing of a set of random stars to a particular region.
 
In the first few lines of code We draw a black rectangle the size of the canvas as a backdrop and translate the origin to the center. Below this We create the circular clipping path by drawing an arc. By calling the clip method the clipping path is created. Clipping paths are also part of the canvas save state. If we wanted to keep the original clipping path we could have saved the canvas state before creating the new one.
 
Everything that’s drawn after creating the clipping path will only appear inside that path. You can see this clearly in the linear gradient that’s drawn next. After this a set of 50 randomly positioned and scaled stars is drawn (I’m using a custom function for this). Again the stars only appear inside the defined clipping path.

Example

<!DOCTYPE HTML>
<html>
    <head>
        <title>Canvas tutorial</title>
        <script>
            function draw(){
                var ctx = document.getElementById('canvas').getContext('2d');
                ctx.fillRect(0, 0, 150, 150);
                ctx.translate(75, 75);
                
                // Create a circular clipping path
                ctx.beginPath();
                ctx.arc(0, 0, 60, 0, Math.PI * 2, true);
                ctx.clip();
                
                // draw background
                var lingrad = ctx.createLinearGradient(0, -75, 0, 75);
                lingrad.addColorStop(0, '#232256');
                lingrad.addColorStop(1, '#143778');
                
                ctx.fillStyle = lingrad;
                ctx.fillRect(-75, -75, 150, 150);
                
                // draw stars
                for (var j = 1; j < 50; j++) {
                    ctx.save();
                    ctx.fillStyle = '#fff';
                    ctx.translate(75 - Math.floor(Math.random() * 150), 75 - 
					Math.floor(Math.random() * 150));
                    drawStar(ctx, Math.floor(Math.random() * 4) + 2);
                    ctx.restore();
                }
                
            }
            
            function drawStar(ctx, r){
                ctx.save();
                ctx.beginPath()
                ctx.moveTo(r, 0);
                for (var i = 0; i < 9; i++) {
                    ctx.rotate(Math.PI / 5);
                    if (i % 2 == 0) {
                        ctx.lineTo((r / 0.525731) * 0.200811, 0);
                    }
                    else {
                        ctx.lineTo(r, 0);
                    }
                }
                ctx.closePath();
                ctx.fill();
                ctx.restore();
            }
        </script>
    </head>
    <body onload="draw();">
        <canvas id="canvas" width="200" height="200">
        </canvas>
    </body>
</html>

Translate

This method is used to move the canvas and its origin to a different point in the grid.
translate(x, y)
This method takes two arguments. x is the amount the canvas is moved to the left or right, and y is the amount it’s moved up or down (illustrated by the image on the right).
It’s a good idea to save the canvas state before doing any transformations. In most cases, it is just easier to call the restore method than having to do a reverse translation to return to the original state. Also if you’re translating inside a loop and don’t save and restore the canvas state, you might end up missing part of your drawing, because it was drawn outside the canvas edge.

Example

<!DOCTYPE HTML>
<html>
    <head>
        <title>Canvas tutorial</title>
        <script>
            function draw(){
                var ctx = document.getElementById('canvas').getContext('2d');
                ctx.fillRect(0, 0, 300, 300);
                for (var i = 0; i < 3; i++) {
                    for (var j = 0; j < 3; j++) {
                        ctx.save();
                        ctx.strokeStyle = "#9CFF00";
                        ctx.translate(50 + j * 100, 50 + i * 100);
                        drawSpirograph(ctx, 20 * (j + 2) / (j + 1), 
						-8 * (i + 3) / (i + 1), 10);
                        ctx.restore();
                    }
                }
            }
            
            function drawSpirograph(ctx, R, r, O){
                var x1 = R - O;
                var y1 = 0;
                var i = 1;
                ctx.beginPath();
                ctx.moveTo(x1, y1);
                do {
                    if (i > 20000) 
                        break;
                    var x2 = (R + r) * Math.cos(i * Math.PI / 72) 
					- (r + O) * Math.cos(((R + r) / r) * (i * Math.PI / 72))
                    var y2 = (R + r) * Math.sin(i * Math.PI / 72) - 
					(r + O) * Math.sin(((R + r) / r) * (i * Math.PI / 72))
                    ctx.lineTo(x2, y2);
                    x1 = x2;
                    y1 = y2;
                    i++;
                }
                while (x2 != R - O && y2 != 0);
                ctx.stroke();
            }
        </script>
    </head>
    <body onload="draw();">
        <canvas id="canvas" width="200" height="200">
        </canvas>
    </body>
</html>

Saving and restoring state

The canvas save and restore methods are used to save and retrieve the canvas state. The canvas drawing state is basically a snapshot of all the styles and transformations that have been applied. Both methods take no parameters.
 
Canvas states are stored on a stack. Every time the save method is called, the current drawing state is pushed onto the stack. A drawing state consists of

  • The transformations that have been applied (i.e. translate, rotate and scale – see below).
  • The values of strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation properties.
  • The current clipping path, which we’ll see in the next section.
  • You can call the save method as many times as you like.
    Every time the restore method is called, the last saved state is returned from the stack and all saved settings are restored.

    Example

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Canvas tutorial</title>
            <script>
                function draw(){
                    var ctx = document.getElementById('canvas').getContext('2d');
                    
                    // Draw a rectangle with default settings
                    ctx.fillRect(0, 0, 150, 150);
                    // Save the default state
                    ctx.save();
                    // Make changes to the settings
                    ctx.fillStyle = '#09F'
                    // Draw a rectangle with new settings
                    ctx.fillRect(15, 15, 120, 120);
                    
                    ctx.save(); // Save the current state
                    // Make changes to the settings
                    ctx.fillStyle = '#FFF'
                    ctx.globalAlpha = 0.5;
                    
                    // Draw a rectangle with new settings
                    ctx.fillRect(30, 30, 90, 90);
                    
                    ctx.restore(); // Restore previous state
                    // Draw a rectangle with restored settings
                    ctx.fillRect(45, 45, 60, 60);
                    
                    ctx.restore(); // Restore original state
                    // Draw a rectangle with restored settings
                    ctx.fillRect(60, 60, 30, 30);
                }
            </script>
        </head>
        <body onload="draw();">
            <canvas id="canvas" width="200" height="200">
            </canvas>
        </body>
    </html>
    

    Shadows Property

    Using shadows involves just four properties:
    shadowOffsetX = float
    shadowOffsetY = float
    shadowBlur = float
    shadowColor = color

    shadowOffsetX and shadowOffsetY indicate how far the shadow should extend from the object in the X and Y directions; these values aren’t affected by the current transformation matrix. Use negative values to cause the shadow to extend up or to the left, and positive values to cause the shadow to extend down or to the right. These are both 0 by default.
    shadowBlur indicates the size of the blurring effect; this value doesn’t correspond to a number of pixels and is not affected by the current transformation matrix. The default value is 0.
    shadowColor is a standard CSS color value indicating the color of the shadow effect; by default, it is fully-transparent black.

    A shadowed text example

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Canvas tutorial</title>
            <script>
                function draw(){
                    var ctx = document.getElementById('canvas').getContext('2d');
                    
                    ctx.shadowOffsetX = 2;
                    ctx.shadowOffsetY = 2;
                    ctx.shadowBlur = 2;
                    ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
                    
                    ctx.font = "20px Times New Roman";
                    ctx.fillStyle = "Black";
                    ctx.fillText("Sample String", 5, 30);
                }
            </script>
        </head>
        <body onload="draw();">
            <canvas id="canvas" width="200" height="200">
            </canvas>
        </body>
    </html>
    

    createRadialGradient Property

    n this example, We’ve defined four different radial gradients. Because we have control over the start and closing points of the gradient, we can achieve more complex effects than we would normally have in the ‘classic’ radial gradients we see in, for instance, Photoshop. (i.e. a gradient with a single center point where the gradient expands outward in a circular shape.)
     
    In this case, We’ve offset the starting point slightly from the end point to achieve a spherical 3D effect. It’s best to try to avoid letting the inside and outside circles overlap because this results in strange effects which are hard to predict.
     
    The last color stop in each of the four gradients uses a fully transparent color. If you want to have a nice transition from this to the previous color stop, both colors should be equal. This isn’t very obvious from the code because We’ve used two different CSS color methods, but in the first gradient #019F62 = rgba(1,159,98,1)

    Example

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Canvas tutorial</title>
            <script>
                function draw(){
                    var ctx = document.getElementById('canvas').getContext('2d');
                    
                    // Create gradients
                    var radgrad = ctx.createRadialGradient(45, 45, 10, 52, 50, 30);
                    radgrad.addColorStop(0, '#A7D30C');
                    radgrad.addColorStop(0.9, '#019F62');
                    radgrad.addColorStop(1, 'rgba(1,159,98,0)');
                    
                    var radgrad2 = ctx.createRadialGradient(105, 105, 20, 112, 120, 50);
                    radgrad2.addColorStop(0, '#FF5F98');
                    radgrad2.addColorStop(0.75, '#FF0188');
                    radgrad2.addColorStop(1, 'rgba(255,1,136,0)');
                    
                    var radgrad3 = ctx.createRadialGradient(95, 15, 15, 102, 20, 40);
                    radgrad3.addColorStop(0, '#00C9FF');
                    radgrad3.addColorStop(0.8, '#00B5E2');
                    radgrad3.addColorStop(1, 'rgba(0,201,255,0)');
                    
                    var radgrad4 = ctx.createRadialGradient(0, 150, 50, 0, 140, 90);
                    radgrad4.addColorStop(0, '#F4F201');
                    radgrad4.addColorStop(0.8, '#E4C700');
                    radgrad4.addColorStop(1, 'rgba(228,199,0,0)');
                    
                    // draw shapes
                    ctx.fillStyle = radgrad4;
                    ctx.fillRect(0, 0, 150, 150);
                    ctx.fillStyle = radgrad3;
                    ctx.fillRect(0, 0, 150, 150);
                    ctx.fillStyle = radgrad2;
                    ctx.fillRect(0, 0, 150, 150);
                    ctx.fillStyle = radgrad;
                    ctx.fillRect(0, 0, 150, 150);
                }
            </script>
        </head>
        <body onload="draw();">
            <canvas id="canvas" width="200" height="200">
            </canvas>
        </body>
    </html>
    

    createLinearGradient Property

    In this example, We’ve created two different gradients. In the first, We create the background gradient. As you can see, W’ve assigned two colors at the same position. You do this to make very sharp color transitions – in this case from white to green. Normally, it doesn’t matter in what order you define the color stops, but in this special case, it does significantly. If you keep the assignments in the order you want them to appear, this won’t be a problem.
     
    In the second gradient, We didn’t assign the starting color (at position 0.0) since it wasn’t strictly necessary. Assigning the black color at position 0.5 automatically makes the gradient, from the start to this stop, black.
     
    As you can see here, both the strokeStyle and fillStyle properties can accept a canvasGradient object as valid input.

    Example

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Canvas tutorial</title>
            <script>
                function draw(){
                    var ctx = document.getElementById('canvas').getContext('2d');
                    
                    // Create gradients
                    var lingrad = ctx.createLinearGradient(0, 0, 0, 150);
                    lingrad.addColorStop(0, '#00ABEB');
                    lingrad.addColorStop(0.5, '#fff');
                    lingrad.addColorStop(0.5, '#26C000');
                    lingrad.addColorStop(1, '#fff');
                    
                    var lingrad2 = ctx.createLinearGradient(0, 50, 0, 95);
                    lingrad2.addColorStop(0.5, '#000');
                    lingrad2.addColorStop(1, 'rgba(0,0,0,0)');
                    
                    // assign gradients to fill and stroke styles
                    ctx.fillStyle = lingrad;
                    ctx.strokeStyle = lingrad2;
                    
                    // draw shapes
                    ctx.fillRect(10, 10, 130, 130);
                    ctx.strokeRect(50, 50, 50, 50);
                }
            </script>
        </head>
        <body onload="draw();">
            <canvas id="canvas" width="200" height="200">
            </canvas>
        </body>
    </html>
    

    Gradients in Canvas

    Just like any normal drawing program, we can fill and stroke shapes using linear and radial gradients. We create a canvasGradient object by using one of the following methods. We use this object to assign it to the fillStyle or strokeStyle properties.
    createLinearGradient(x1,y1,x2,y2)
    createRadialGradient(x1,y1,r1,x2,y2,r2)

    The createLinearGradient method takes four arguments representing the starting point (x1,y1) and end point (x2,y2) of the gradient.
    The createRadialGradient method takes six arguments. The first three arguments define a circle with coordinates (x1,y1) and radius r1 and the second a circle with coordinates (x2,y2) and radius r2.

    var lineargradient = ctx.createLinearGradient(0,0,150,150);
    var radialgradient = ctx.createRadialGradient(75,75,0,75,75,100);
    

    Once we’ve created a canvasGradient object we can assign colors to it by using the addColorStop method.
    addColorStop(position, color)
    This method takes two arguments. The position must be a number between 0.0 and 1.0 and defines the relative position of the color in the gradient. Setting this to 0.5 for instance would place the color precisely in the middle of the gradient. The color argument must be a string representing a CSS color (ie #FFF, rgba(0,0,0,1),etc).
    You can add as many color stops to a gradient as you need. Below is a very simple linear gradient from white to black.

    var lineargradient = ctx.createLinearGradient(0,0,150,150);
    lineargradient.addColorStop(0,'white');
    lineargradient.addColorStop(1,'black');
    

    Both properties are explained in next tutorials

    lineJoin property

    The lineJoin property determines how two connecting segments (of lines, arcs or curves) with non-zero lengths in a shape are joined together (degenerate segments with zero lengths, whose specified endpoints and control points are exactly at the same position, are skipped).
     
    There are three possible values for this property: round, bevel and miter. By default this property is set to miter. Note that the lineJoin setting has no effect if the two connected segments have the same direction, because no joining area will be added in this case.

    Example

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Canvas tutorial</title>
            <script>
                function draw(){
                    var ctx = document.getElementById('canvas').getContext('2d');
                    var lineJoin = ['round', 'bevel', 'miter'];
                    ctx.lineWidth = 10;
                    for (var i = 0; i < lineJoin.length; i++) {
                        ctx.lineJoin = lineJoin[i];
                        ctx.beginPath();
                        ctx.moveTo(-5, 5 + i * 40);
                        ctx.lineTo(35, 45 + i * 40);
                        ctx.lineTo(75, 5 + i * 40);
                        ctx.lineTo(115, 45 + i * 40);
                        ctx.lineTo(155, 5 + i * 40);
                        ctx.stroke();
                    }
                }
            </script>
        </head>
        <body onload="draw();">
            <canvas id="canvas" width="200" height="200">
            </canvas>
        </body>
    </html>
    

    lineCap property

    The lineCap property determines how the end points of every line are drawn. There are three possible values for this property and those are: butt, round and square. By default this property is set to butt.

    Example

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Canvas tutorial</title>
            <script>
                function draw(){
    				var ctx = document.getElementById('canvas').getContext('2d');
    				var lineCap = ['butt', 'round', 'square'];
    				
    				// Draw guides
    				ctx.strokeStyle = '#09f';
    				ctx.beginPath();
    				ctx.moveTo(10, 10);
    				ctx.lineTo(140, 10);
    				ctx.moveTo(10, 140);
    				ctx.lineTo(140, 140);
    				ctx.stroke();
    				
    				// Draw lines
    				ctx.strokeStyle = 'black';
    				for (var i = 0; i < lineCap.length; i++) {
    					ctx.lineWidth = 15;
    					ctx.lineCap = lineCap[i];
    					ctx.beginPath();
    					ctx.moveTo(25 + i * 50, 10);
    					ctx.lineTo(25 + i * 50, 140);
    					ctx.stroke();
    				}
    			}
            </script>
        </head>
        <body onload="draw();">
            <canvas id="canvas" width="200" height="200">
            </canvas>
        </body>
    </html>
    

    lineWidth

    This property sets the current line thickness. Values must be positive numbers. By default this value is set to 1.0 units.
     
    The line width is the thickness of the stroke centered on the given path. In other words, the area that’s drawn extends to half the line width on either side of the path. Because canvas coordinates do not directly reference pixels, special care must be taken to obtain crisp horizontal and vertical lines.
     
    In the example below, 10 straight lines are drawn with increasing line widths. The line on the far left is 1.0 units wide. However, the leftmost and all other odd-integer-width thickness lines do not appear crisp, because of the path’s positioning.

    Example

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Canvas tutorial</title>
            <script>
                function draw(){
                    var ctx = document.getElementById('canvas').getContext('2d');
                    for (var i = 0; i < 10; i++) {
                        ctx.lineWidth = 1 + i;
                        ctx.beginPath();
                        ctx.moveTo(5 + i * 14, 5);
                        ctx.lineTo(5 + i * 14, 140);
                        ctx.stroke();
                    }
                }
            </script>
        </head>
        <body onload="draw();">
            <canvas id="canvas" width="200" height="200">
            </canvas>
        </body>
    </html>
    

    Scaling Images

    the second variant of the drawImage method adds two new parameters and it allows us to place scaled images on the canvas.
    drawImage(image, x, y, width, height)
    Where width and height is the image’s size on the target canvas.

    Example

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Canvas tutorial</title>
            <script>
                function draw(){
                    var ctx = document.getElementById('canvas').getContext('2d');
                    var img = new Image();
                    img.onload = function(){
                        for (var i = 0; i < 4; i++) {
                            for (var j = 0; j < 3; j++) {
                                ctx.drawImage(img, j * 50, i * 38, 50, 38);
                            }
                        }
                    };
                    img.src = '123.png';
                }
            </script>
        </head>
        <body onload="draw();">
            <canvas id="canvas" width="200" height="200">
            </canvas>
        </body>
    </html>
    

    Drawing Images with drawImage

    Once we have a reference to our source image object we can use the drawImage method to render it to the canvas. As we we’ll see later the drawImage method is overloaded and has three different variants. In its most basic form it looks like this.
    drawImage(image, x, y)
    Where image is a reference to our image or canvas object. x and y form the coordinate on the target canvas where our image should be placed.

    Example

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Canvas tutorial</title>
            <script>
                function draw(){
                    var ctx = document.getElementById('canvas').getContext('2d');
                    var img = new Image();
                    img.onload = function(){
                        ctx.drawImage(img, 0, 0);
                        ctx.beginPath();
                        ctx.moveTo(30, 96);
                        ctx.lineTo(70, 66);
                        ctx.lineTo(103, 76);
                        ctx.lineTo(170, 15);
                        ctx.stroke();
                    };
                    img.src = 'sampleImage.png'; 
                }
            </script>
        </head>
        <body onload="draw();">
            <canvas id="canvas" width="200" height="200">
            </canvas>
        </body>
    </html>
    

    Bezier and quadratic curves

    These are generally used to draw complex organic shapes.
     
    The difference between these can best be described using the image on the right. A quadratic Bézier curve has a start and an end point and just one control point while a cubic Bézier curve uses two control points.
     
    The x and y parameters in both these methods are the coordinates of the end point. cp1x and cp1y are the coordinates of the first control point, and cp2x and cp2y are the coordinates of the second control point.
     
    Using quadratic and cubic Bézier curves can be quite challenging, because unlike vector drawing software like Adobe Illustrator, we don’t have direct visual feedback as to what we’re doing. This makes it pretty hard to draw complex shapes. In the following example, we’ll be drawing some simple organic shapes, but if you have the time and, most of all, the patience, much more complex shapes can be created.
     
    There’s nothing very difficult in these examples. In both cases we see a succession of curves being drawn which finally result in a complete shape.

    Example 1

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Canvas tutorial</title>
            <script>
                function draw(){
                   var ctx = document.getElementById('canvas').getContext('2d');
                    // Quadratric curves example
                    ctx.beginPath();
                    ctx.moveTo(75, 25);
                    ctx.quadraticCurveTo(25, 25, 25, 62.5);
                    ctx.quadraticCurveTo(25, 100, 50, 100);
                    ctx.quadraticCurveTo(50, 120, 30, 125);
                    ctx.quadraticCurveTo(60, 120, 65, 100);
                    ctx.quadraticCurveTo(125, 100, 125, 62.5);
                    ctx.quadraticCurveTo(125, 25, 75, 25);
                    ctx.stroke();
                }
            </script>
        </head>
        <body onload="draw();">
            <canvas id="canvas" width="200" height="200">
            </canvas>
        </body>
    </html>
    

    Output

    Untitled

    It is possible to convert any quadratic Bézier curve to a cubic Bézier curve by correctly computing both cubic Bézier control points from the single quadratic Bézier control point, although the reverse is NOT true. An exact conversion of a cubic Bézier curve to a quadratic Bézier curve is only possible if the cubic term is zero, more commonly a subdivision method is used to approximate a cubic Bézier using multiple quadratic Bézier curves.

    Example 2

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Canvas tutorial</title>
            <script>
                function draw(){
                    var ctx = document.getElementById('canvas').getContext('2d');
                    // Bezier curves example
                    ctx.beginPath();
                    ctx.moveTo(75, 40);
                    ctx.bezierCurveTo(75, 37, 70, 25, 50, 25);
                    ctx.bezierCurveTo(20, 25, 20, 62.5, 20, 62.5);
                    ctx.bezierCurveTo(20, 80, 40, 102, 75, 120);
                    ctx.bezierCurveTo(110, 102, 130, 80, 130, 62.5);
                    ctx.bezierCurveTo(130, 62.5, 130, 25, 100, 25);
                    ctx.bezierCurveTo(85, 25, 75, 37, 75, 40);
                    ctx.fill();
                }
            </script>
        </head>
        <body onload="draw();">
            <canvas id="canvas" width="200" height="200">
            </canvas>
        </body>
    </html>
    

    Output

    Untitled2

    Drawing Arcs

    For drawing arcs or circles we use the arc method. The specification also describes the arcTo method, which is supported by Safari and Firefox, but wasn’t implemented in the older Gecko browsers.
    arc(x, y, radius, startAngle, endAngle, anticlockwise)
    This method takes five parameters: x and y are the coordinates of the circle’s center. Radius is self explanatory. The startAngle and endAngle parameters define the start and end points of the arc in radians. The starting and closing angle are measured from the x axis. The anticlockwise parameter is a Boolean value which when true draws the arc anticlockwise, otherwise in a clockwise direction.
    Note: Angles in the arc function are measured in radians, not degrees. To convert degrees to radians you can use the following JavaScript expression: var radians = (Math.PI/180)*degrees.

    Example

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Canvas tutorial</title>
            <script>
                function draw(){
                    var ctx = document.getElementById('canvas').getContext('2d');
                    for (var i = 0; i < 4; i++) {
                        for (var j = 0; j < 3; j++) {
                            ctx.beginPath();
                            var x = 25 + j * 50; // x coordinate
                            var y = 25 + i * 50; // y coordinate
                            var radius = 20; // Arc radius
                            var startAngle = 0; // Starting point on circle
    						// End point on circle
                            var endAngle = Math.PI + (Math.PI * j) / 2; 
    						// clockwise or anticlockwise
                            var anticlockwise = i % 2 == 0 ? false : true; 
                            ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
                            
                            if (i > 1) {
                                ctx.fill();
                            }
                            else {
                                ctx.stroke();
                            }
                        }
                    }
                }
            </script>
        </head>
        <body onload="draw();">
            <canvas id="canvas" width="200" height="200">
            </canvas>
        </body>
    </html>
    

    Drawing Lines

    For drawing straight lines we use the lineTo method.
     
    lineTo(x, y);
     
    This method takes two arguments – x and y, – which are the coordinates of the line’s end point. The starting point is dependent on previous drawn paths, where the end point of the previous path is the starting point for the following, etc.

    Example

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Canvas tutorial</title>
            <script>
                function draw(){
                    var ctx = document.getElementById('canvas').getContext('2d');
                    ctx.beginPath();
                    ctx.moveTo(25, 25);
                    ctx.lineTo(105, 25);
                    ctx.lineTo(25, 105);
                    ctx.closePath(); // for completing triangle
                    ctx.stroke();
                }
            </script>
        </head>
        <body onload="draw();">
            <canvas id="canvas" width="200" height="200">
            </canvas>
        </body>
    </html>