JavaScript - tutorial - 14 - canvas

Revision:


Content

canvas - the basics drawing in the canvas canvas properties methods colors, styles, and shadows in canvas canvas line styles rectangles paths transformations text image drawing pixel manipulation compositing canvas examples


canvas - the basics

top

basic usage

The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript. The "canvas" element is only a container for graphics. You must use JavaScript to actually draw the graphics. A canvas is a rectangular area on an HTML page, which, by default, has no border and no content. The markup looks like this: <canvas id="myCanvas" width="200" height="100"></canvas>

Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

Examples

canvas

code:
                    <div class="spec">
                        <canvas id="canvas_b1" width="200" height="200"><p>canvas</p></canvas>
                    </div>
                    <style>
                        #canvas_b1{margin-left: 4vw; top:1vw; border: 0.5vw solid black; 
                            background-image: linear-gradient(green, blue, red);}
                    </style>
                    <script>
                        let one = document.getElementById("canvas_b1");
                        let ctx = one.getContext("2d");
                        ctx.moveTo(0,0);
                        ctx.lineTo(400,400);
                        ctx.strokeStyle = "magenta";
                        ctx.lineWidth = 15;
                        ctx.stroke();    
                    </script>

                

how a canvas works!

First of all, always specify an "id attribute" (to be referred to in a script), and a "width" and "height" attribute to define the size of the canvas. To add a border, use the "style" attribute.

Add a Javascript: after creating the rectangular canvas area, you must add a JavaScript to do the drawing.

The getContext() method returns an object that provides methods and properties for drawing on the canvas. The properties and methods of the getContext("2d") object can be used to draw text, lines, boxes, circles, and more on the canvas.

drawing a canvas

step 1: find the canvas element : finding the "canvas" element is done by using the HTML DOM method getElementById(): "var canvas = document.getElementById("myCanvas");".

step 2: create a drawing object : the getContext() is a built-in HTML object, with properties and methods for drawing: "var ctx = canvas.getContext("2d");"

step 3: draw on the canvas : to draw on the canvas, you have to set the fill style of the drawing object to a certain color: 'ctx.fillStyle = "#FF0000";'.

Examples - draw a canvas

canvas-b2
code:
                    <div class="spec">
                        <canvas id="canvas_b2" width="200" height="200">canvas-b2</canvas>
                    </div>
                    <style>
                        #canvas_b2{margin-left: 4vw; border: 0.5vw solid blue; background-image: radial-gradient(ellipse, green, black, red);}
                    </style>
                    <script>
                        let two = document.getElementById("canvas_b2");
                        let ctx_two = two.getContext("2d");
                        ctx_two.beginPath();
                        ctx_two.arc(100,100,60,0,2*Math.PI);
                        ctx_two.strokeStyle = "magenta";
                        ctx_two.lineWidth = 15;
                        ctx_two.stroke();
                    </script>
                
canvas-b4
code:
                        <div class="spec">
                            <canvas id="canvas_b4" width="200" height="200">canvas-b4</canvas>
                        </div>
                        <style>
                            #canvas_b4{margin-left: 4vw; border: 0.5vw solid green; background-image: radial-gradient(circle, lightgray, grey, black); }
                        </style>
                        <script>
                            let four = document.getElementById('canvas_b4');
                            let ctx_four = four.getContext('2d');
                            let gradient_four = ctx_four.createRadialGradient(100,100,5,90,160,160);
                            gradient_four.addColorStop(0, "red");
                            gradient_four.addColorStop(1, "white");
                            ctx_four.fillStyle = gradient_four;
                            ctx_four.fillRect(50, 50, 90, 90);
                        </script>
                
canvas-b5
code:
                    <div class="spec">
                        <canvas id="canvas_b5" width="200" height="200">canvas-b5</canvas>
                    </div>
                    <style>
                        #canvas_b5{margin-left: 4vw; border: 0.5vw solid green; background-image: radial-gradient(ellipse, gray, burlywood, orange);}
                    </style>
                    <script>
                        let five = document.getElementById('canvas_b5');
                        let ctx_five = five.getContext('2d');
                        let gradient_five = ctx_five.createRadialGradient(100,100,5,90,160,160);
                        gradient_five.addColorStop(0, "green");
                        gradient_five.addColorStop(1, "white");
                        ctx_five.fillStyle = gradient_five;
                        ctx_five.fillRect(60, 60, 150, 90);
                    </script>
                

canvas drawing - playing with pictures

image to use:

Holiday

canvas to fill:

canvas-b6
code:
                    <div class=" grid spec">
                        <div>
                            <h4>image to use:</h4> 
                            <img id="Holiday" src="../pics/1.jpg" width="200" height="200" alt="Holiday"/>
                        </div>
                        <div>
                            <h4>canvas to fill:</h4>
                            <canvas id="canvas_b6" width="200" height="200">canvas-b6</canvas>
                        </div>
                        <a><button onclick="canvas()">try it</button></a>
                    </div>
                    <style>
                        #canvas_b6{margin-left: 4vw;border: 0.5vw solid yellow;}
                    </style>
                    <script>
                        function canvas(){
                            let six = document.getElementById('canvas_b6');
                            let ctx_six = six.getContext('2d');
                            let img = document.getElementById('Holiday');
                            ctx_six.drawImage(img,0,0,200,200);
                        }
                    </script>
                

drawing in the canvas

top

canvas coordinates

The HTML canvas is a two-dimensional grid: the upper-left corner of the canvas has the coordinates (0,0). The fillRect(0,0,150,75) method means: start at the upper-left corner (0,0) and draw a 150x75 pixels rectangle.

draw a line

To draw a straight line on a canvas, use the following methods:

moveTo(x,y) defines the starting point of the line.

lineTo(x,y) defines the ending point of the line.

To actually draw the line, you must use one of the "ink" methods, like stroke().

Example

Your browser does not support the canvas element. Your browser does not support the canvas element.
code:
                    <div class="spec">
                        <canvas id="canvas_d1" width="200" height="200" style="border:1px solid black;">
                            Your browser does not support the canvas element.
                        </canvas>
                        <canvas id="canvas_d1a" width="200" height="200" style="border:1px solid black;">
                            Your browser does not support the canvas element.
                        </canvas>
                    </div>
                    <script>
                        var draw1 = document.getElementById("canvas_d1");
                        var ctx_draw1 = draw1.getContext("2d");
                        ctx_draw1.moveTo(0,0);
                        ctx_draw1.lineTo(200,200);
                        ctx_draw1.stroke();
                        var draw1a = document.getElementById("canvas_d1a");
                        var ctx_draw1a = draw1a.getContext("2d");
                        ctx_draw1a.moveTo(200,0);
                        ctx_draw1a.lineTo(0,200);
                        ctx_draw1a.stroke();
                    </script>
                

draw a circle

To draw a circle on a canvas, use the following methods:

beginPath() begins a path.

arc(x,y,r,startangle,endangle) creates an arc/curve. To create a circle with arc(): set "start angle" to 0 and "end angle" to 2*Math.PI. The x and y parameters define the x- and y-coordinates of the center of the circle. The r parameter defines the radius of the circle.

Example

Your browser does not support the HTML canvas tag. Your browser does not support the HTML canvas tag.
code:
                    <div class="spec">
                        <canvas id="canvas-d2" width="200" height="200" style="border:0.1vw solid black;">
                            Your browser does not support the HTML canvas tag.</canvas>
                        <canvas id="canvas-d2a" width="200" height="200" style="border:0.1vw solid darkgreen;">
                            Your browser does not support the HTML canvas tag.</canvas>
                    </div>
                    <script>
                        var draw2 = document.getElementById("canvas-d2");
                        var ctx_draw2 = draw2.getContext("2d");
                        ctx_draw2.beginPath();
                        ctx_draw2.arc(95,95,60,0,2*Math.PI);
                        ctx_draw2.stroke();
        
                        var draw2a = document.getElementById("canvas-d2a");
                        var ctx_draw2a = draw2a.getContext("2d");
                        ctx_draw2a.beginPath();
                        ctx_draw2a.arc(90,70,40,0,2*Math.PI);
                        ctx_draw2a.stroke();
                    </script>
                

draw a text

To draw text on a canvas, the most important property and methods are:

font defines the font properties for the text.

fillText(text,x,y) draws "filled" text on the canvas.

strokeText(text,x,y) draws text on the canvas (no fill)

To add color to the text, use the fillStyle() method.

Examples - fillText()

Your browser does not support the HTML canvas tag. Your browser does not support the HTML canvas tag.
code:
                    <div class="spec">
                        <canvas id="canvas-d3" width="200" height="200" style="border:0.1vw solid black;">
                            Your browser does not support the HTML canvas tag.</canvas>
                        <canvas id="canvas-d3a" width="200" height="200" style="border:0.1vw solid black;">
                                Your browser does not support the HTML canvas tag.</canvas>
                    </div>
                    <script>
                        var draw3 = document.getElementById("canvas-d3");
                        var ctx_draw3 = draw3.getContext("2d");
                        ctx_draw3.font = "2vw Arial";
                        ctx_draw3.fillText("Hello World",20,50);
        
                        var draw3a = document.getElementById("canvas-d3a");
                        var ctx_draw3a = draw3a.getContext("2d");
                        ctx_draw3a.font = "2vw Helvetia";
                        ctx_draw3a.fillText("Welcome",20,100);
                    </script>
                

Examples - strokeText()

Your browser does not support the HTML canvas tag. Your browser does not support the HTML canvas tag.
code:
                    <div class="spec">
                        <canvas id="canvas-d4" width="300" height="200" style="border:0.1vw solid black;">
                            Your browser does not support the HTML canvas tag.</canvas>
                        <canvas id="canvas-d4a" width="300" height="200" style="border:0.1vw solid black;">
                            Your browser does not support the HTML canvas tag.</canvas>
                    </div>
                    <script>
                        var draw4 = document.getElementById("canvas-d4");
                        var ctx_draw4 = draw4.getContext("2d");
                        ctx_draw4.font = "2vw Arial";
                        ctx_draw4.strokeText("Hello World",10,50);
        
                        var draw4a = document.getElementById("canvas-d4a");
                        var ctx_draw4a = draw4a.getContext("2d");
                        ctx_draw4a.font = "3vw Helvetia";
                        ctx_draw4a.strokeText("Welcome",10,100);
                    </script>
                

draw linear gradient

Gradients can be used to fill rectangles, circles, lines, text, etc. Shapes on the canvas are not limited to solid colors.

createLinearGradient(x,y,x1,y1) creates a linear gradient.

Once we have a gradient object, we must add two or more color stops. The addColorStop() method specifies the color stops, and its position along the gradient. Gradient positions can be anywhere between 0 to 1.

To use the gradient, set the fillStyle or strokeStyle property to the gradient, then draw the shape (rectangle, text, or a line).

Examples - linear gradient

Your browser does not support the HTML canvas tag. Your browser does not support the HTML canvas tag.
code:
                    <div class="spec">
                        <canvas id="canvas-d5" width="300" height="200" style="border:0.1vw solid black;">
                            Your browser does not support the HTML canvas tag.</canvas>
                        <canvas id="canvas-d5a" width="300" height="200" style="border:0.1vw solid blue;">
                            Your browser does not support the HTML canvas tag.</canvas>
                    </div>
                    <script>
                        var draw5 = document.getElementById("canvas-d5");
                        var ctx_draw5 = draw5.getContext("2d");
                        // Create gradient
                        var grd = ctx_draw5.createLinearGradient(0, 0, 200, 0);
                        grd.addColorStop(0, "red");
                        grd.addColorStop(1, "white");
                        // Fill with gradient
                        ctx_draw5.fillStyle = grd;
                        ctx_draw5.fillRect(10, 10, 200, 150);
        
                        var draw5a = document.getElementById("canvas-d5a");
                        var ctx_draw5a = draw5a.getContext("2d");
                        // Create gradient
                        var grd = ctx_draw5a.createLinearGradient(50, 10, 10, 100);
                        grd.addColorStop(1, "blue");
                        grd.addColorStop(0, "green");
                        // Fill with gradient
                        ctx_draw5a.fillStyle = grd;
                        ctx_draw5a.fillRect(10, 10, 250, 150);
                    </script>
                

draw circular gradient

Gradients can be used to fill rectangles, circles, lines, text, etc. Shapes on the canvas are not limited to solid colors.

createRadialGradient(x,y,r,x1,y1,r1) creates a radial/circular gradient.

Once we have a gradient object, we must add two or more color stops. The addColorStop() method specifies the color stops, and its position along the gradient. Gradient positions can be anywhere between 0 to 1.

To use the gradient, set the fillStyle or strokeStyle property to the gradient, then draw the shape (rectangle, text, or a line).

Examples -circular gradient

Your browser does not support the HTML canvas tag. Your browser does not support the HTML canvas tag.
code:
                <div class="spec">
                    <canvas id="canvas-d6" width="300" height="200" style="border:0.1vw solid black;">
                        Your browser does not support the HTML canvas tag.</canvas>
                    <canvas id="canvas-d6a" width="300" height="200" style="border:0.1vw solid black;">
                        Your browser does not support the HTML canvas tag.</canvas>
                </div>
                <script>
                    var draw6 = document.getElementById("canvas-d6");
                    var ctx_draw6 = draw6.getContext("2d");
                    // Create gradient
                    var grd_b = ctx_draw6.createRadialGradient(75, 50, 5, 90, 60, 100);
                    grd_b.addColorStop(0, "red");
                    grd_b.addColorStop(1, "white");
                    // Fill with gradient
                    ctx_draw6.fillStyle = grd_b;
                    ctx_draw6.fillRect(10, 10, 250, 150);
        
                    var draw6a = document.getElementById("canvas-d6a");
                    var ctx_draw6a = draw6a.getContext("2d");
                    // Create gradient
                    var grd_b = ctx_draw6.createRadialGradient(105, 70, 15, 110, 60, 150);
                    grd_b.addColorStop(1, "yellow");
                    grd_b.addColorStop(0, "green");
                    // Fill with gradient
                    ctx_draw6a.fillStyle = grd_b;
                    ctx_draw6a.fillRect(10, 10, 250, 150);
        
                </script>
            

draw image

To draw an image on a canvas, use the following method:drawImage(image,x,y).

Examples - draw image

holiday
Your browser does not support the HTML canvas tag.

canvas to fill:

code:
                <div class="grid1 spec">
                    <div>
                        <img id="flowers" src="../pics/img_flowers.jpg" alt="holiday" width="300" height="200"/>
                    </div>
                    <div>
                        <canvas id="canvas-d7" width="300" height="200" style="border:0.1vw solid black;">
                            Your browser does not support the HTML canvas tag.</canvas>
                        <p class="spec">canvas to fill:</p>
                    </div>
                    <p class="spec"><button onclick="drawImage()">Try it</button></p>    
                </div>
                <script>
                    function drawImage() {
                        var draw7 = document.getElementById("canvas-d7");
                        var ctx_draw7 = draw7.getContext("2d");
                        var img = document.getElementById("flowers");
                        ctx_draw7.drawImage(flowers , 0 , 0, 300, 200);
                    }
                </script>
            

canvas properties

top

fillstyle

The fillStyle property sets or returns the color, gradient, or pattern used to "fill the drawing". Property values include:

color: a CSS color value that indicates the fill color of the drawing. Default value is #000000.

gradient: a gradient object (linear or radial) used to fill the drawing

pattern: a pattern object to use to fill the drawing.

strokeStyle

The strokeStyle property sets or returns the color, gradient, or pattern used for "strokes". Property values include:

color: a CSS color value that indicates the stroke color of the drawing. Default value is #000000.

gradient: a gradient object (linear or radial) used to create a gradient stroke.

pattern: a pattern object used to create a pattern stroke.

shadowColor

The shadowColor property sets or returns the color to use for "shadows". Property values include:

color: the CSS color value to use for shadows. Default value is #000000.

shadowBlur

The shadowBlur property sets or returns the blur level for "shadows". Property values include:

number: the blur level for the shadow.

shadowOffsetX

The shadowOffsetX property sets or returns the "horizontal" distance of the shadow from the shape. "shadowOffsetX=0" indicates that the shadow is right behind the shape. "shadowOffsetX=20" indicates that the shadow starts 20 pixels to the right (from the shape's left position). "shadowOffsetX=-20" indicates that the shadow starts 20 pixels to the left (from the shape's left position).Property values include:

>number: a positive or negative number that defines the horizontal distance of the shadow from the shape.

shadowOffsetY

The shadowOffsetY property sets or returns the "vertical" distance of the shadow from the shape. "shadowOffsetY = 0" indicates that the shadow is right behind the shape. "shadowOffsetY = 20" indicates that the shadow starts 20 pixels below the shape's top position. "shadowOffsetY = -20" indicates that the shadow starts 20 pixels above the shape's top position. Property values include:

number: a positive or negative number that defines the vertical distance of the shadow from the shape

Example covering above properties

Examples

code:
                <div class="spec">
                    <canvas id="canvas_prop2" width="300" height="200" style="border-radius: 1vw; 
                    border: 0.2vw solid black;"></canvas> 
                    <canvas id="canvas_prop2a" width="300" height="200" style="border-radius: 1vw; 
                    border: 0.2vw solid black;"></canvas> 
                </div>
                <script>
                    var prop2 = document.getElementById("canvas_prop2");
                    var ctx_prop2 = prop2.getContext("2d");
                    ctx_prop2.fillStyle = "orange";
                    ctx_prop2.shadowBlur= 20;
                    ctx_prop2.shadowColor = "black";
                    ctx_prop2.shadowOffsetX = 40;
                    ctx_prop2.shadowOffsetY = 30;
                    ctx_prop2.fillRect(30, 30, 200, 120);
        
                    var prop2a = document.getElementById("canvas_prop2a");
                    var ctx_prop2a = prop2a.getContext("2d");
                    ctx_prop2a.fillStyle = "lightgreen";
                    ctx_prop2a.shadowBlur= 30;
                    ctx_prop2a.shadowColor = "yellow";
                    ctx_prop2a.shadowOffsetX = 30;
                    ctx_prop2a.shadowOffsetY = 30;
                    ctx_prop2a.fillRect(10, 10, 220, 140);
                </script>
            

lineCap

The lineCap property sets or returns the style of the end caps for a line. The value "round" and "square" make the lines slightly longer. Property values include:

butt: default; a flat edge is added to each end of the line.

round: a rounded end cap is added to each end of the line.

square: a square end cap is added to each end of the line.

lineJoin

The lineJoin property sets or returns the type of corner created, when two lines meet.

bevel: creates a beveled corner.

round: creates a rounded corner.

miter: default; creates a sharp corner.

lineWidth

The lineWidth property sets or returns the current line width, in pixels. Property values include:

number: the current line width, in pixels.

miterLimit

The miterLimit property sets or returns the maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet. The miterLimit property works only if the "lineJoin" attribute is "miter". The miter length grows bigger as the angle of the corner gets smaller. To prevent the miter length from being too long, we can use the miterLimit property. If the miter length exceeds the miterLimit value, the corner will be displayed as lineJoin type "bevel". Property values include:

number: a positive number that specifies the maximum miter length. If the current miter length exceeds the miterLimit, the corner will display as lineJoin "bevel".

Example covering these properties

Examples

code:
                <div class="spec">
                    <canvas id="canvas_prop3" width="300" height="200" style="border-radius: 1vw; 
                    border: 0.2vw solid black;"></canvas> 
                    <canvas id="canvas_prop3a" width="300" height="200" style="border-radius: 1vw; 
                    border: 0.2vw solid blue;"></canvas> 
                </div>
                <script>
                    var prop3 = document.getElementById("canvas_prop3");
                    var ctx_prop3 = prop3.getContext("2d");
                    ctx_prop3.beginPath();
                    ctx_prop3.lineWidth = 10;
                    ctx_prop3.lineCap = "butt";
                    ctx_prop3.moveTo(20, 20);
                    ctx_prop3.lineTo(250, 20);
                    ctx_prop3.stroke();
       
                    ctx_prop3.beginPath();
                    ctx_prop3.lineJoin = "round";
                    ctx_prop3.moveTo(20, 40);
                    ctx_prop3.lineTo(250, 80);
                    ctx_prop3.lineTo(20, 100);
                    ctx_prop3.stroke();
       
                    ctx_prop3.lineWidth=10;
                    ctx_prop3.lineJoin = "miter";
                    ctx_prop3.miterLimit = 5;
                    ctx_prop3.moveTo(20, 140);
                    ctx_prop3.lineTo(170, 150);
                    ctx_prop3.lineTo(20, 170);
                    ctx_prop3.stroke()
       
                    var prop3a = document.getElementById("canvas_prop3a");
                    var ctx_prop3a = prop3a.getContext("2d");
                    ctx_prop3a.beginPath();
                    ctx_prop3a.lineWidth = 25;
                    ctx_prop3a.lineCap = "square";
                    ctx_prop3a.moveTo(20, 20);
                    ctx_prop3a.lineTo(250, 20);
                    ctx_prop3a.stroke();
                    
                    ctx_prop3a.beginPath();
                    ctx_prop3a.lineJoin = "round";
                    ctx_prop3a.moveTo(250, 50);
                    ctx_prop3a.lineTo(50, 90);
                    ctx_prop3a.lineTo(250, 100);
                    ctx_prop3a.stroke();
       
                    ctx_prop3a.lineWidth=10;
                    ctx_prop3a.lineJoin = "miter";
                    ctx_prop3a.miterLimit = 10;
                    ctx_prop3a.moveTo(220, 140);
                    ctx_prop3a.lineTo(20, 150);
                    ctx_prop3a.lineTo(220, 170);
                    ctx_prop3a.stroke()
                </script>
             

font

The font property sets or returns the current font properties for text content on the canvas. The font property uses the same syntax as the CSS font property. Property values include:

font-style: specifies the font style. Possible values: normal, italic, oblique.

font-variant: specifies the font variant. Possible values: normal, small-caps.

font-weight: specifies the font weight. Possible values: normal, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, 900.

font-size/line-height: specifies the font size and the line-height, in pixels.

font-family: specifies the font family.

caption: use the font captioned controls (like buttons, drop-downs, etc.).

icon: use the font used to label icons.

menu: use the font used in menus (drop-down menus and menu lists).

message-box: use the font used in dialog boxes.

small-caption: use the font used for labeling small controls.

status-bar: use the fonts used in window status bar.

textAlign

The textAlign property sets or returns the current alignment for text content, according to the anchor point. Normally, the text will START in the position specified, however, if you set textAlign="right" and place the text in position 150, it means that the text should END in position 150. Property values include:

start: default. The text starts at the specified position.

end: the text ends at the specified position.

center: the center of the text is placed at the specified position.

left: the text starts at the specified position.

right: the text ends at the specified position.

textBaseline

The textBaseline property sets or returns the current text baseline used when drawing text. Property values include:

alphabetic: default. The text baseline is the normal alphabetic baseline.

top: the text baseline is the top of the em square.

hanging: the text baseline is the hanging baseline.

middle: the text baseline is the middle of the em square.

ideographic: the text baseline is the ideographic baseline.

bottom: the text baseline is the bottom of the bounding box.

Example covering these properties

Examples

code:
                    <div class="spec">
                        <canvas id="canvas_prop4" width="500" height="300" style="border-radius: 1vw; 
                        border: 0.2vw solid black;"></canvas> 
                        <canvas id="canvas_prop5" width="500" height="300" style="border-radius: 1vw; 
                        border: 0.2vw solid black;"></canvas> 
                    </div>
                    <script>
                        var prop4 = document.getElementById("canvas_prop4");
                        var ctx_prop4 = prop4.getContext("2d");
                        // Create a red line in position 150
                        ctx_prop4.strokeStyle = "red";
                        ctx_prop4.moveTo(200, 10);
                        ctx_prop4.lineTo(200, 270);
                        ctx_prop4.lineWidth= 10;
                        ctx_prop4.stroke();
                        ctx_prop4.font = "1.2vw Arial";
                        // Show the different textAlign values
                        ctx_prop4.textAlign = "start";
                        ctx_prop4.fillText("textAlign=start", 205, 40);
                        ctx_prop4.textAlign = "end";
                        ctx_prop4.fillText("textAlign=end", 195, 80);
                        ctx_prop4.textAlign = "left";
                        ctx_prop4.fillText("textAlign=left", 205, 120);
                        ctx_prop4.textAlign = "center";
                        ctx_prop4.fillText("textAlign=center", 195, 160);
                        ctx_prop4.textAlign = "right";
                        ctx_prop4.fillText("textAlign=right", 205, 200);
        
                        var prop5 = document.getElementById("canvas_prop5");
                        var ctx_prop5 = prop5.getContext("2d");
                        //Draw a red line at y=100
                        ctx_prop5.strokeStyle = "red";
                        ctx_prop5.lineWidth = 10;
                        ctx_prop5.moveTo(5, 150);
                        ctx_prop5.lineTo(550, 150);
                        ctx_prop5.stroke();
                        ctx_prop5.font = "1.15vw Arial"
                        //Place each word at y=100 with different textBaseline values
                        ctx_prop5.textBaseline = "top"; 
                        ctx_prop5.fillText("Top", 5, 155); 
                        ctx_prop5.textBaseline = "bottom"; 
                        ctx_prop5.fillText("Bottom", 105, 150); 
                        ctx_prop5.textBaseline = "middle"; 
                        ctx_prop5.fillText("Middle", 205, 152); 
                        ctx_prop5.textBaseline = "alphabetic"; 
                        ctx_prop5.fillText("Alphabetic", 305, 145); 
                        ctx_prop5.textBaseline = "hanging"; 
                        ctx_prop5.fillText("Hanging", 405, 155); 
                    </script>
                

width

The width property returns the width of an ImageData object, in pixels.

height

The height property returns the height of an ImageData object, in pixels.

data

The data property returns an object that contains image data of the specified ImageData object. For every pixel in an ImageData object there are four pieces of information, the RGBA values: R - the color red (from 0-255), G - the color green (from 0-255), B - the color blue (from 0-255), A - the alpha channel (from 0-255; 0 is transparent and 255 is fully visible). The color/alpha information is held in an array, and is stored in the data property of the ImageData object.

Examples

code:
                <div class="spec">
                    <canvas id="canvas_prop6" width="400" height="200" style="border-radius: 1vw;
                     border: 0.2vw solid black;"></canvas> 
                </div>
                <script>
                    var prop6 = document.getElementById("canvas_prop6");
                    var ctx_prop6 = prop6.getContext("2d");
                    var imgData = ctx_prop6.createImageData(100, 100);
        
                    var i;
                    for (i = 0; i < imgData.data.length; i += 4) {
                    imgData.data[i+0] = 255;
                    imgData.data[i+1] = 0;
                    imgData.data[i+2] = 0;
                    imgData.data[i+3] = 255;
                    }
                    ctx_prop6.putImageData(imgData, 10, 10);
                </script>
            

globalAlpha

The globalAlpha property sets or returns the current alpha or transparency value of the drawing. The globalAlpha property value must be a number between 0.0 (fully transparent) and 1.0 (no transparancy). Property values include:

number: the transparency value. Must be a number between 0.0 (fully transparent) and 1.0 (no transparancy).

Examples

code:
                <div class="spec">
                    <canvas id="canvas_prop7" width="400" height="200" 
                    style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                </div>
                <script>
                    var prop7 = document.getElementById("canvas_prop7");
                    var ctx_prop7 = prop7.getContext("2d");
                    ctx_prop7.fillStyle = "red";
                    ctx_prop7.fillRect(20, 20, 100, 110);
                    //Turn transparency on
                    ctx_prop7.globalAlpha = 0.2;
                    ctx_prop7.fillStyle = "blue"; 
                    ctx_prop7.fillRect(40, 40, 130, 120); 
                    ctx_prop7.fillStyle = "green"; 
                    ctx_prop7.fillRect(60, 60, 150, 130);
                </script>
            

globalCompositeOperation

The globalCompositeOperation property sets or returns how a source (new) image are drawn onto a destination (existing) image. "source image" = drawings you are about to place onto the canvas. "destination image" = drawings that are already placed onto the canvas. Property values include:

source-over: default. Displays the source image over the destination image.

source-atop: displays the source image on top of the destination image. The part of the source image that is outside the destination image is not shown.

source-in: displays the source image in to the destination image. Only the part of the source image that is INSIDE the destination image is shown, and the destination image is transparent.

source-out: displays the source image out of the destination image. Only the part of the source image that is OUTSIDE the destination image is shown, and the destination image is transparent.

destination-over: displays the destination image over the source image.

destination-atop: displays the destination image on top of the source image. The part of the destination image that is outside the source image is not shown.

destination-in: displays the destination image in to the source image. Only the part of the destination image that is INSIDE the source image is shown, and the source image is transparent.

destination-out: displays the destination image out of the source image. Only the part of the destination image that is OUTSIDE the source image is shown, and the source image is transparent.

lighter: displays the source image + the destination image.

copy: displays the source image. The destination image is ignored.

xor: the source image is combined by using an exclusive OR with the destination image.

Examples

code:
                <canvas class="spec" id="canvas_prop8" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var prop8 = document.getElementById("canvas_prop8");
                    var ctx_prop8 = prop8.getContext("2d");
                    ctx_prop8.fillStyle = "red";
                    ctx_prop8.fillRect(20, 20, 100, 80);
                    ctx_prop8.fillStyle = "blue";
                    ctx_prop8.globalCompositeOperation = "source-over";
                    ctx_prop8.fillRect(50, 50, 100, 80);
                    ctx_prop8.fillStyle = "red";
                    ctx_prop8.fillRect(200, 20, 100, 80);
                    ctx_prop8.fillStyle = "blue";
                    ctx_prop8.globalCompositeOperation = "destination-over";
                    ctx_prop8.fillRect(230, 50, 100, 80);
                </script>
            

methods

createImageData(): creates a new, blank ImageData object: width, height, imagedata.

getImageData(): returns an ImageData object that copies the pixel data for the specified rectangle on a canvas: x, y, width, height.

putImageData(): puts the image data (from a specified ImageData object) back onto the canvas: imgData, x, y, dirtyX (optional), dirtyY (optional), dirtyWidth (optional), dirtyHeight (optional).

Examples

code:
                <div class="spec">
                    <canvas id="canvas_pixA" width="300" height="200" style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                    <button onclick="copyDataA()">Copy</button>
                </div>
                <script>
                    var pixA = document.getElementById("canvas_pixA");
                    var ctx_pixA = pixA.getContext("2d");
                    ctx_pixA.fillStyle = "red";
                    ctx_pixA.fillRect(10, 10, 50, 50);
        
                    function copyDataA() {
                        var imgData = ctx_pixA.getImageData(10, 10, 50, 50);
                        ctx_pixA.putImageData(imgData, 10, 70);
                    }
                </script>
            

methods

top

createLinearGradient()

The createLinearGradient() method creates a linear gradient object. The gradient can be used to fill rectangles, circles, lines, text, etc. Parameter values include:

x0: the x-coordinate of the start point of the gradient.

y0: the y-coordinate of the start point of the gradient.

x1: the x-coordinate of the end point of the gradient.

y1: the y-coordinate of the end point of the gradient.

Examples

code:
                <canvas class="spec" id="method1" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    function method1() {
                        const ctx_method1 = document.getElementById('method1').getContext('2d');
                        let radgrad = ctx_method1.createLinearGradient(0, 0, 200, 0);
                        radgrad.addColorStop(0, 'green');
                        radgrad.addColorStop(1, 'red');
                        
                        let radgrad2 = ctx_method1.createLinearGradient(200, 0, 400, 200);
                        radgrad2.addColorStop(0, 'blue');
                        radgrad2.addColorStop(1, 'orange');
                    
                        ctx_method1.fillStyle = radgrad2;
                        ctx_method1.fillRect(200, 0, 400, 200);
                        ctx_method1.fillStyle = radgrad;
                        ctx_method1.fillRect(0, 0, 200, 200);
                    }
                    method1();
                </script>
            

createPattern()

The createPattern()method repeats the specified element in the specified direction. The element can be an image, video, or another "canvas" element. The repeated element can be used to draw/fill rectangles, circles, lines etc. Parameter values include:

image: specifies the image, canvas, or video element of the pattern to use.

repeat: default; the pattern repeats both horizontally and vertically.

repeat-x: the pattern repeats only horizontally.

repeat-y: the pattern repeats only vertically.

no-repeat: the pattern will be displayed only once (no repeat).

Examples

Image to use:

canvas:


code:
                <div class="spec">
                    <p>Image to use:</p>
                    <img src="../pics/search.png" id="search" style="width:2vw; height:2vw;">
                    <p>canvas:</p>
                    <canvas id="method2" width="400" height="200" 
                    style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> <br>
                    <button onclick="method2('repeat')">Repeat</button> 
                    <button onclick="method2('repeat-x')">Repeat-x</button> 
                    <button onclick="method2('repeat-y')">Repeat-y</button> 
                    <button onclick="method2('no-repeat')">No-repeat</button>   
                </div>
                <script>
                    function method2(direction) {
                        var method2 = document.getElementById("method2");
                        var ctx_method2 = method2.getContext("2d");
                        ctx_method2.clearRect(0, 0, method2.width, method2.height); 
                        var img = document.getElementById("search")
                        var pat = ctx_method2.createPattern(img, direction);
                        ctx_method2.rect(0, 0, 150, 100);
                        ctx_method2.fillStyle = pat;
                        ctx_method2.fill();
                    }
                method2();
                </script>
            

createRadialGradient()

The createRadialGradient()method creates a radial/circular gradient object. The gradient can be used to fill rectangles, circles, lines, text, etc. Parameter values include:

x0: the x-coordinate of the starting circle of the gradient.

y0: the y-coordinate of the starting circle of the gradient.

r0: the radius of the starting circle.

x1: the x-coordinate of the ending circle of the gradient.

y1: the y-coordinate of the ending circle of the gradient.

r1: the radius of the ending circle.

Examples

code:
                <canvas class="spec" id="method3" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    function method3() {
                        const ctx_method3 = document.getElementById('method3').getContext('2d');
                    
                        let radgrad_method3 = ctx_method3.createRadialGradient(45, 45, 10, 52, 50, 50);
                        radgrad_method3.addColorStop(0, '#A7D30C');
                        radgrad_method3.addColorStop(0.9, '#019F62');
                        radgrad_method3.addColorStop(1, 'rgba(1, 159, 98, 0)');
                        
                        let radgrad2_method3 = ctx_method3.createRadialGradient(175, 115, 30, 192, 120, 50);
                        radgrad2_method3.addColorStop(0, '#FF5F98');
                        radgrad2_method3.addColorStop(0.75, '#FF0188');
                        radgrad2_method3.addColorStop(1, 'rgba(255, 1, 136, 0)');
                    
                        ctx_method3.fillStyle = radgrad2_method3;
                        ctx_method3.fillRect(0, 0, 250, 250);
                        ctx_method3.fillStyle = radgrad_method3;
                        ctx_method3.fillRect(0, 0, 250, 250);
                    }
                    method3();
                </script>
            

addColorStop()

The addColorStop()method specifies the colors and position in a gradient object. The addColorStop() method is used together with createLinearGradient() or createRadialGradient(). Parameter values include:

stop: a value between 0.0 and 1.0 that represents the position between start and end in a gradient.

color: a CSS color value to display at the stop position .

Examples

code:
                <canvas class="spec" id="method4" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method4 = document.getElementById("method4");
                    var ctx_method4 = method4.getContext("2d");
                    var grd_method4 = ctx_method4.createLinearGradient(0, 0, 270, 0);
                    grd_method4.addColorStop(0, "black");
                    grd_method4.addColorStop("0.3", "magenta");
                    grd_method4.addColorStop("0.5", "blue");
                    grd_method4.addColorStop("0.6", "green");
                    grd_method4.addColorStop("0.8", "yellow");
                    grd_method4.addColorStop(1, "red");
                    ctx_method4.fillStyle = grd_method4;
                    ctx_method4.fillRect(20, 20, 250, 150);
                </script>
            

rect()

The rect()method creates a rectangle. Parameter values include:

x: the x-coordinate of the upper-left corner of the rectangle.

y: the y-coordinate of the upper-left corner of the rectangle.

width: the width of the rectangle, in pixels .

height: the height of the rectangle, in pixels .

Examples

code:
                <canvas class="spec" id="method5" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method5 = document.getElementById("method5");
                    var ctx_method5 = method5.getContext("2d");
                    // Red rectangle
                    ctx_method5.beginPath();
                    ctx_method5.lineWidth = "6";
                    ctx_method5.strokeStyle = "red";
                    ctx_method5.rect(5, 5, 290, 140);
                    ctx_method5.stroke();
                    // Green rectangle
                    ctx_method5.beginPath();
                    ctx_method5.lineWidth = "14";
                    ctx_method5.strokeStyle = "green";
                    ctx_method5.rect(30, 30, 80, 80);
                    ctx_method5.stroke();
                    // Blue rectangle
                    ctx_method5.beginPath();
                    ctx_method5.lineWidth = "2";
                    ctx_method5.strokeStyle = "blue";
                    ctx_method5.rect(50, 50, 200,120);
                    ctx_method5.stroke();
                </script>
            

fillRect()

The fillRect()method draws a "filled" rectangle. The default color of the fill is black. Parameter values include:

x: the x-coordinate of the upper-left corner of the rectangle.

y: the y-coordinate of the upper-left corner of the rectangle.

width: the width of the rectangle, in pixels.

height: the height of the rectangle, in pixels.

Examples

code:
                <canvas class="spec" id="method6" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method6 = document.getElementById("method6");
                    var ctx_method6 = method6.getContext("2d");
                    // Red rectangle
                    ctx_method6.fillStyle = "red";
                    ctx_method6.fillRect(20, 20, 100, 100);
                    // Green rectangle
                    ctx_method6.fillStyle = "green";
                    ctx_method6.fillRect(60, 60, 100, 100);
                    // // Blue rectangle
                    ctx_method6.fillStyle = "blue";
                    ctx_method6.fillRect(100, 100, 100, 100);
                </script>
            

strokeRect()

The strokeRect()method draws a rectangle (no fill). The default color of the stroke is black.

x: the x-coordinate of the upper-left corner of the rectangle.

y: the y-coordinate of the upper-left corner of the rectangle.

width: the width of the rectangle, in pixels.

height: the height of the rectangle, in pixels.

Examples

code:
                <canvas class="spec" id="method7" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method7 = document.getElementById("method7");
                    var ctx_method7 = method7.getContext("2d");
                    // Red rectangle
                    ctx_method7.strokeStyle = "red";
                    ctx_method7.strokeRect(20, 20, 100, 100);
                    // Green rectangle
                    ctx_method7.strokeStyle = "green";
                    ctx_method7.strokeRect(60, 60, 100, 100);
                    // // Blue rectangle
                    ctx_method7.strokeStyle = "blue";
                    ctx_method7.strokeRect(100, 100, 100, 100);
                </script>
            

clearRect()

The clearRect()method clears the specified pixels within a given rectangle.

x: the x-coordinate of the upper-left corner of the rectangle to clear.

y: the y-coordinate of the upper-left corner of the rectangle to clear.

width: the width of the rectangle to clear, in pixels.

height: the height of the rectangle to clear, in pixels.

Examples

code:
                <canvas class="spec" id="method8" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method8 = document.getElementById("method8");
                    var ctx_method8 = method8.getContext("2d");
                    //red rectangle
                    ctx_method8.fillStyle = "red";
                    ctx_method8.fillRect(10, 10, 100, 150);
                    ctx_method8.clearRect(20, 20, 50, 50);
                    // Green rectangle
                    ctx_method8.fillStyle = "green";
                    ctx_method8.fillRect(60, 60, 100, 100);
                    ctx_method8.clearRect(80, 80, 50, 50);
                    // Blue rectangle
                    ctx_method8.fillStyle = "blue";
                    ctx_method8.fillRect(100, 100, 100, 100);
                    ctx_method8.clearRect(130, 130, 50, 50);
                </script>
            

fill()

The fill()method fills the current drawing (path). The default color is black.

Examples

code:
                <canvas class="spec" id="method9" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method9 = document.getElementById("method9");
                    var ctx_method9 = method9.getContext("2d");
                    //red rectangle
                    ctx_method9.beginPath();
                    ctx_method9.rect(20, 20, 150, 150);
                    ctx_method9.fillStyle = "red";
                    ctx_method9.fill();
                    // green rectangle
                    ctx_method9.beginPath();
                    ctx_method9.rect(40, 40, 150, 150);
                    ctx_method9.fillStyle = "green";
                    ctx_method9.fill();
                    // Blue rectangle
                    ctx_method9.beginPath();
                    ctx_method9.rect(60, 60, 150, 150);
                    ctx_method9.fillStyle = "blue";
                    ctx_method9.fill();
                </script>
            

stroke()

The stroke()method actually draws the path you have defined with all those moveTo() and lineTo() methods. The default color is black.

Examples

code:
                <canvas class="spec" id="method10" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method10 = document.getElementById("method10");
                    var ctx_method10 = method10.getContext("2d");
                    //red stroke
                    ctx_method10.beginPath();
                    ctx_method10.moveTo(20, 20);
                    ctx_method10.lineTo(20, 150);
                    ctx_method10.lineTo(70, 150);
                    ctx_method10.strokeStyle = "red";
                    ctx_method10.stroke();
                    //green stroke
                    ctx_method10.beginPath();
                    ctx_method10.moveTo(120, 20);
                    ctx_method10.lineTo(120, 150);
                    ctx_method10.lineTo(170, 150);
                    ctx_method10.strokeStyle = "green";
                    ctx_method10.stroke();
                    //red stroke
                    ctx_method10.beginPath();
                    ctx_method10.moveTo(220, 20);
                    ctx_method10.lineTo(220, 150);
                    ctx_method10.lineTo(270, 150);
                    ctx_method10.strokeStyle = "blue";
                    ctx_method10.stroke();
                </script>
            

beginPath()

The beginPath()method begins a path, or resets the current path.

Examples

code:
                <canvas class="spec" id="method11" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method11 = document.getElementById("method11");
                    var ctx_method11 = method11.getContext("2d");
                    ctx_method11.lineWidth="5";
                    //red stroke
                    ctx_method11.beginPath();
                    ctx_method11.moveTo(20, 20);
                    ctx_method11.lineTo(70, 150);
                    ctx_method11.lineTo(20, 150);
                    ctx_method11.strokeStyle = "red";
                    ctx_method11.stroke();
                    //green stroke
                    ctx_method11.beginPath();
                    ctx_method11.moveTo(140, 20);
                    ctx_method11.lineTo(180, 150);
                    ctx_method11.lineTo(100, 120);
                    ctx_method11.strokeStyle = "green";
                    ctx_method11.stroke();
                    //red stroke
                    ctx_method11.beginPath();
                    ctx_method11.moveTo(320, 20);
                    ctx_method11.lineTo(320, 150);
                    ctx_method11.lineTo(70, 20);
                    ctx_method11.strokeStyle = "blue";
                    ctx_method11.stroke();
                </script>
            

moveTo()

The moveTo()method moves the path to the specified point in the canvas, without creating a line. Parameter values include:

x: the x-coordinate of where to move the path to.

y: the y-coordinate of where to move the path to.

Examples

code:
                <canvas class="spec" id="method12" width="400" height="200" 
                style=" border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method12 = document.getElementById("method12");
                    var ctx_method12 = method12.getContext("2d");
                    ctx_method12.lineWidth="10";
                    //red stroke
                    ctx_method12.beginPath();
                    ctx_method12.moveTo(20, 20);
                    ctx_method12.lineTo(100, 150);
                    ctx_method12.strokeStyle = "red";
                    ctx_method12.stroke();
                    //green stroke
                    ctx_method12.beginPath();
                    ctx_method12.moveTo(80, 20);
                    ctx_method12.lineTo(190, 150);
                    ctx_method12.strokeStyle = "green";
                    ctx_method12.stroke();
                    //red stroke
                    ctx_method12.beginPath();
                    ctx_method12.moveTo(220, 20);
                    ctx_method12.lineTo(320, 150);
                    ctx_method12.strokeStyle = "blue";
                    ctx_method12.stroke();
                </script>
            

closePath()

The closePath()method creates a path from the current point back to the starting point.

Examples

code:
                <canvas class="spec" id="method13" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method13 = document.getElementById("method13");
                    var ctx_method13 = method13.getContext("2d");
                    ctx_method13.lineWidth = "7"
                    //red stroke
                    ctx_method13.beginPath();
                    ctx_method13.moveTo(20, 20);
                    ctx_method13.lineTo(20, 150);
                    ctx_method13.lineTo(70, 150);
                    ctx_method13.closePath();
                    ctx_method13.strokeStyle = "red";
                    ctx_method13.stroke();
                    //green stroke
                    ctx_method13.beginPath();
                    ctx_method13.moveTo(120, 20);
                    ctx_method13.lineTo(120, 150);
                    ctx_method13.lineTo(170, 150);
                    ctx_method13.closePath();
                    ctx_method13.strokeStyle = "green";
                    ctx_method13.stroke();
                    ctx_method13.fillStyle = "lightgreen";
                    ctx_method13.fill();
                    //red stroke
                    ctx_method13.beginPath();
                    ctx_method13.moveTo(220, 20);
                    ctx_method13.lineTo(220, 150);
                    ctx_method13.lineTo(270, 150);
                    ctx_method13.closePath();
                    ctx_method13.strokeStyle = "blue";
                    ctx_method13.stroke();
                </script>
            

lineTo()

The lineTo()method adds a new point and creates a line TO that point FROM the last specified point in the canvas (this method does not draw the line).

x: the x-coordinate of where to create the line to.

y: the y-coordinate of where to create the line to .

Examples

code:
                <canvas class="spec" id="method14" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method14 = document.getElementById("method14");
                    var ctx_method14 = method14.getContext("2d");
                    ctx_method14.lineWidth = "7"
                    //red stroke
                    ctx_method14.beginPath();
                    ctx_method14.moveTo(20, 20);
                    ctx_method14.lineTo(20, 150);
                    ctx_method14.lineTo(70, 150);
                    ctx_method14.strokeStyle = "red";
                    ctx_method14.stroke();
                    //green stroke
                    ctx_method14.beginPath();
                    ctx_method14.moveTo(120, 20);
                    ctx_method14.lineTo(120, 150);
                    ctx_method14.lineTo(170, 150);
                    ctx_method14.strokeStyle = "green";
                    ctx_method14.stroke();
                    //red stroke
                    ctx_method14.beginPath();
                    ctx_method14.moveTo(220, 20);
                    ctx_method14.lineTo(220, 150);
                    ctx_method14.lineTo(270, 150);
                    ctx_method14.strokeStyle = "blue";
                    ctx_method14.stroke();
                </script>
            

clip()

The clip()method clips a region of any shape and size from the original canvas. Once a region is clipped, all future drawing will be limited to the clipped region (no access to other regions on the canvas). You can however save the current canvas region using the save() method before using the clip() method, and restore it (with the restore() method) any time in the future.

Examples

code:
                <canvas class="spec" id="method15" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method15 = document.getElementById("method15");
                    var ctx_method15 = method15.getContext("2d");
                    ctx_method15.rect(20, 20, 150, 150);
                    ctx_method15.stroke();
                    ctx_method15.clip();
                    // draw rectangle after clip
                    ctx_method15.fillStyle = "blue";
                    ctx_method15.fillRect(30, 30, 80, 80);
                </script>
            

quadraticCurveTo()

The quadraticCurveTo()method adds a point to the current path by using the specified control points that represent a quadratic Bézier curve. A quadratic Bézier curve requires two points. The first point is a control point that is used in the quadratic Bézier calculation and the second point is the ending point for the curve. The starting point for the curve is the last point in the current path. If a path does not exist, use the beginPath() and moveTo() methods to define a starting point. Parameter values include:

cpx: the x-coordinate of the Bézier control point.

cpy: the y-coordinate of the Bézier control point.

x: the x-coordinate of the ending point.

y: the y-coordinate of the ending point.

Examples

code:
                <canvas class="spec" id="method16" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    function teken() {
                        let method16 = document.getElementById('method16');
                        if (method16.getContext) {
                            let ctx_method16 = method16.getContext('2d');
                            // Quadratric curves example
                            ctx_method16.beginPath();
                            ctx_method16.moveTo(20, 20);
                            ctx_method16.quadraticCurveTo(10, 250, 50, 20);
                            ctx_method16.quadraticCurveTo(10, 250, 100, 20);
                            ctx_method16.quadraticCurveTo(10, 250, 150, 20);
                            ctx_method16.quadraticCurveTo(10, 250, 200, 20);
                            ctx_method16.quadraticCurveTo(10, 250, 250, 20);
                            ctx_method16.quadraticCurveTo(10, 250, 300, 22);
                            ctx_method16.strokeStyle = "green";
                            ctx_method16.lineWidth = "7";
                            ctx_method16.stroke();
                        }
                    }
                    teken();
                </script>
            

bezierCurveTo()

The bezierCurveTo()method adds a point to the current path by using the specified control points that represent a cubic Bézier curve. A cubic bezier curve requires three points. The first two points are control points that are used in the cubic Bézier calculation and the last point is the ending point for the curve. The starting point for the curve is the last point in the current path. If a path does not exist, use the beginPath() and moveTo() methods to define a starting point. Parameter values include:

cp1x: the x-coordinate of the first Bézier control point.

cp1y: the y-coordinate of the first Bézier control point.

cp2x: the x-coordinate of the second Bézier control point.

cp2y: the y-coordinate of the second Bézier control point.

x: the x-coordinate of the ending point.

y: the y-coordinate of the ending point.

Examples

code:
                <canvas class="spec" id="method17" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                function draw() {
                    const method17 = document.getElementById('method17');
                        if (method17.getContext) {
                            const ctx_method17 = method17.getContext('2d');
                        // Cubic curves example
                            ctx_method17.beginPath();
                            ctx_method17.moveTo(75, 40);
                            ctx_method17.bezierCurveTo(75, 37, 70, 25, 50, 25);
                            ctx_method17.bezierCurveTo(20, 25, 20, 62.5, 20, 62.5);
                            ctx_method17.bezierCurveTo(20, 80, 40, 102, 75, 120);
                            ctx_method17.bezierCurveTo(110, 102, 130, 80, 130, 62.5);
                            ctx_method17.bezierCurveTo(130, 62.5, 130, 25, 100, 25);
                            ctx_method17.bezierCurveTo(85, 25, 75, 37, 75, 40);
                            ctx_method17.fillStyle = "red";
                            ctx_method17.fill();
                        }
                    }
                    draw();
                </script>
            

arc()

The arc()method creates an arc/curve (used to create circles, or parts of circles). To create a circle with arc(): set start angle to 0 and end angle to 2*Math.PI. Parameter values include:

x: the x-coordinate of the center of the circle.

y: the y-coordinate of the center of the circle.

r: the radius of the circle.

sAngle: the starting angle, in radians (0 is at the 3 o'clock position of the arc's circle) .

eAngle: the ending angle, in radians.

counterclockwise: optional; specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise.

Examples

code:
                <canvas class="spec" id="method18" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method18 = document.getElementById("method18");
                    var ctx_method18 = method18.getContext("2d");
                    ctx_method18.beginPath();
                    ctx_method18.arc(100, 100, 60, 0, 2 * Math.PI);
                    ctx_method18.fillStyle = "lightgreen";
                    ctx_method18.fill();
                    ctx_method18.strokeStyle = "red";
                    ctx_method18.stroke();
                </script>
            

arcTo()

The arcTo()method creates an arc/curve between two tangents on the canvas. Parameter values include:

x1: the x-coordinate of the first tangent.

y1: the y-coordinate of the first tangent.

x2: the x-coordinate of the second tangent.

y2: the y-coordinate of the second tangent.

r: the radius of the arc.

Examples

code:
                <canvas class="spec" id="method19" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method19 = document.getElementById("method19");
                    var ctx_method19 = method19.getContext("2d");
                    ctx_method19.lineWidth = "7";
                    //blue arc
                    ctx_method19.beginPath();
                    ctx_method19.moveTo(20,20);
                    ctx_method19.lineTo(100, 20);
                    ctx_method19.arcTo(150, 20, 150,70, 50);
                    ctx_method19.lineTo(150, 140);
                    ctx_method19.strokeStyle = "blue"
                    ctx_method19.stroke();
                    // green arc
                    ctx_method19.beginPath();
                    ctx_method19.moveTo(220,20);
                    ctx_method19.lineTo(300, 20);
                    ctx_method19.arcTo(350, 20, 350,370, 50);
                    ctx_method19.lineTo(350, 140);
                    ctx_method19.strokeStyle = "green"
                    ctx_method19.stroke();
                </script>
            

isPointInPath()

The isPointInPath()method returns true if the specified point is in the current path, otherwise false. Parameter values include:

x: the x-coordinate to test.

y: the y-coordinate to test.

Examples

code:
                <canvas class="spec" id="method20" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method20 = document.getElementById("method20");
                    var ctx_method20 = method20.getContext("2d");
                    ctx_method20.rect(20, 20, 150, 150);
                    if (ctx_method20.isPointInPath(20,20)){
                        ctx_method20.strokeStyle = "red";
                        ctx_method20.stroke();
                    };
                </script>
            

scale()

The scale()method scales the current drawing, bigger or smaller. If you scale a drawing, all future drawings will also be scaled. The positioning will also be scaled. If you "scale(2,2);" drawings will be positioned twice as far from the left and top of the canvas as you specify. Parameter values include:

scalewidth: scales the width of the current drawing (1=100%, 0.5=50%, 2=200%, etc.).

scaleheight: scales the height of the current drawing (1=100%, 0.5=50%, 2=200%, etc.).

Examples

code:
                <canvas id="method21" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method21 = document.getElementById("method21");
                    var ctx_method21 = method21.getContext("2d");
                    ctx_method21.strokeStyle = "red";
                    ctx_method21.strokeRect(5, 5, 25, 15);
                    ctx_method21.scale(2, 2);
                    ctx_method21.strokeRect(5, 5, 25, 15);
                    ctx_method21.scale(2, 2);
                    ctx_method21.strokeRect(5, 5, 25, 15);
                    ctx_method21.scale(2, 2);
                    ctx_method21.strokeRect(5, 5, 25, 15);
                </script>
            

rotate()

The rotate()method rotates the current drawing. The rotation will only affect drawings made AFTER the rotation is done. Parameter values include:

angle: the rotation angle, in radians. To calculate from degrees to radians: degrees*Math.PI/180. Example: to rotate 5 degrees, specify the following: 5*Math.PI/180 .

Examples

code:
                <canvas class="spec" id="method22" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method22 = document.getElementById("method22");
                    var ctx_method22 = method22.getContext("2d");
                    //red square
                    ctx_method22.fillStyle = "red";
                    ctx_method22.rotate(20 * Math.PI / 180);
                    ctx_method22.fillRect(50, 20, 100, 50);
                    // blue square
                    ctx_method22.fillStyle = "blue";
                    ctx_method22.rotate(5 * Math.PI / 180);
                    ctx_method22.fillRect(220, 10, 100, 50);
                </script>
            

translate()

The translate()method remaps the (0,0) position on the canvas. When you call a method such as fillRect() after translate(), the value is added to the x- and y-coordinate values. Parameter values include:

x: the value to add to horizontal (x) coordinates.

y: the value to add to vertical (y) coordinates.

Examples

code:
                <canvas class="spec" id="method23" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method23 = document.getElementById("method23");
                    var ctx_method23 = method23.getContext("2d");
                    ctx_method23.fillRect(20, 20, 150, 150);
                    ctx_method23.translate(190, 0);
                    ctx_method23.fillRect(20, 20, 150, 150);
                </script>
            

transform()

The transform()method replaces the current transformation matrix. It lets you scale, rotate, move, and skew the current context. The transformation will only affect drawings made after the transform() method is called. The transform() method behaves relatively to other transformations made by rotate(), scale(), translate(), or transform(). Example: If you already have set your drawing to scale by two, and the transform() method scales your drawings by two, your drawings will now scale by four. Check out the setTransform() method, which does not behave relatively to other transformations. Parameter values include:

a: horizontal scaling.

b: horizontal skewing.

c: vertical skewing.

d: vertical scaling.

e: horizontal moving.

f: vertical moving.

Examples

code:
                <canvas class="spec" id="method24" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method24 = document.getElementById("method24");
                    var ctx_method24 = method24.getContext("2d");
                    ctx_method24.fillStyle = "yellow";
                    ctx_method24.fillRect(0, 0, 250, 100)
                    ctx_method24.transform(1, 0.5, -0.5, 1, 30, 10);
                    ctx_method24.fillStyle = "red";
                    ctx_method24.fillRect(0, 0, 250, 100);
                    ctx_method24.transform(1, 0.5, -0.5, 1, 30, 10);
                    ctx_method24.fillStyle = "blue";
                    ctx_method24.fillRect(0, 0, 250, 100);
                </script>
            

setTransform()

The setTransform()method resets the current transform to the identity matrix, and then runs transform() with the same arguments. In other words, the setTransform() method lets you scale, rotate, move, and skew the current context. The transformation will only affect drawings made after the setTransform method is called. Parameter values include:

a: horizontal scaling.

b: horizontal skewing.

c: vertical skewing.

d: vertical scaling.

e: horizontal moving.

f: vertical moving.

Examples

code:
                <canvas class="spec" id="method25" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method25 = document.getElementById("method25");
                    var ctx_method25 = method25.getContext("2d");
                    ctx_method25.fillStyle = "yellow";
                    ctx_method25.fillRect(0, 0, 250, 100)
                    ctx_method25.setTransform(1,0.5, -0.5, 1, 30, 10);
                    ctx_method25.fillStyle = "red";
                    ctx_method25.fillRect(0, 0, 250, 100);
                    ctx_method25.setTransform(1,0.7, -0.9, 1, 30, 10);
                    ctx_method25.fillStyle = "blue";
                    ctx_method25.fillRect(0, 0, 250, 100);
                </script>
            

fillText()

The fillText()method draws filled text on the canvas. The default color of the text is black. Parameter values include:

text: specifies the text that will be written on the canvas.

x: the x coordinate where to start painting the text (relative to the canvas).

y: the y coordinate where to start painting the text (relative to the canvas).

maxWidth: optional. The maximum allowed width of the text, in pixels.

Examples

code:
                <canvas class="spec" id="method26" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method26 = document.getElementById("method26");
                    var ctx_method26 = method26.getContext("2d");
                    ctx_method26.font = "20px Georgia";
                    ctx_method26.fillText("Hello World!", 10, 50);
                    ctx_method26.font = "30px Verdana";
                    // Create gradient
                    var gradient_method26 = ctx_method26.createLinearGradient(0, 0, method26.width, 0);
                    gradient_method26.addColorStop("0", "magenta");
                    gradient_method26.addColorStop("0.5", "blue");
                    gradient_method26.addColorStop("1.0", "red");
                    // Fill with gradient
                    ctx_method26.fillStyle = gradient_method26;
                    ctx_method26.fillText("Big smile!", 10, 100);
                </script>
            

strokeText()

The strokeText()method draws text (with no fill) on the canvas. The default color of the text is black. Parameter values include:

text: specifies the text that will be written on the canvas.

x: the x coordinate where to start painting the text (relative to the canvas).

y: the y coordinate where to start painting the text (relative to the canvas).

maxWidth: optional. The maximum allowed width of the text, in pixels.

Examples

code:
                <canvas class="spec" id="method27" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method27 = document.getElementById("method27");
                    var ctx_method27 = method27.getContext("2d");
                    ctx_method27.font = "2vw Georgia";
                    ctx_method27.fillText("How are you doing!?!", 10, 50);
                    ctx_method27.font = "2.5vw Verdana";
                    // Create gradient
                    var gradient_method27 = ctx_method27.createLinearGradient(0, 0, method27.width, 0);
                    gradient_method27.addColorStop("0", "magenta");
                    gradient_method27.addColorStop("0.5", "blue");
                    gradient_method27.addColorStop("1.0", "red");
                    // Fill with gradient
                    ctx_method27.strokeStyle = gradient_method27;
                    ctx_method27.strokeText("A very Big smile!", 10, 100);
                </script>
            

measureText()

The measureText()method returns an object that contains the width of the specified text, in pixels. Use this method if you need to know the width of a text, before writing it on the canvas. Parameter values include:

text: the text to be measured.

Examples

code:
                <canvas class="spec" id="method28" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method28 = document.getElementById("method28");
                    var ctx_method28 = method28.getContext("2d");
                    ctx_method28.font = "2vw Arial";
                    var txt_method28 = "How are you doing!?"
                    ctx_method28.fillText("width:" + ctx_method28.measureText(txt_method28).width, 10, 50);
                    ctx_method28.fillText(txt_method28, 10, 100);
                </script>
            

drawImage()

The drawImage()method draws an image, canvas, or video onto the canvas. The drawImage() method can also draw parts of an image, and/or increase/reduce the image size. Parameter values include:

img: specifies the image, canvas, or video element to use.

sx: optional. The x coordinate where to start clipping.

sy: optional. The y coordinate where to start clipping.

swidth: optional. The width of the clipped image.

sheight: optional. The height of the clipped image.

x: the x coordinate where to place the image on the canvas.

y: the y coordinate where to place the image on the canvas.

width: optional. The width of the image to use (stretch or reduce the image) .

height: optional. The height of the image to use (stretch or reduce the image) .

Examples

Image to use:

smiley

canvas:


code:
                <div class="spec">
                    <p>Image to use:</p>
                    <img id="smiley" style="width:10%; height: auto" src="../pics/smiley.png" alt="smiley">
                    <p>canvas:</p>
                    <canvas id="method29" width="400" height="200" style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> <br>
                </div>
                <script>
                    var method29 = document.getElementById("method29");
                    var ctx_method29 = method29.getContext("2d");
                    window.addEventListener('load', () =>{
                        var img = document.getElementById("smiley");
                        ctx_method29.drawImage(img, 10, 10);
                    });
                </script>
            

createImageData()

The createImageData()method creates a new, blank ImageData object. The new object's pixel values are transparent black by default. For every pixel in an ImageData object there are four pieces of information, the RGBA values: R - The color red (from 0-255),G - The color green (from 0-255), B - The color blue (from 0-255), A - The alpha channel (from 0-255; 0 is transparent and 255 is fully visible), So, transparent black indicates: (0,0,0,0). The color/alpha information is held in an array, and since the array contains 4 pieces of information for every pixel, the array's size is 4 times the size of the ImageData object: width*height*4. (An easier way to find the size of the array, is to use ImageDataObject.data.length). The array containing the color/alpha information is stored in the data property of the ImageData object. Parameter values include:

width: the width of the new ImageData object, in pixels.

height: the height of the new ImageData object, in pixels.

imageData: anotherImageData object.

Examples

code:
                <canvas class="spec" id="method30" width="400" height="200" 
                style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                <script>
                    var method30 = document.getElementById("method30");
                    var ctx_method30 = method30.getContext("2d");
                    var imgData = ctx_method30.createImageData(100, 100);
                    var i;
                    for (i = 0; i <imgData.data.length; i += 4) {
                        imgData.data[i+0] = 255;
                        imgData.data[i+1] = 0;
                        imgData.data[i+2] = 0;
                        imgData.data[i+3] = 255;
                    }
                    ctx_method30.putImageData(imgData, 10, 10);
                </script>
            

getImageData()

The getImageData()method returns an ImageData object that >copies the pixel data for the specified rectangle on a canvas. The ImageData object is not a picture, it specifies a part (rectangle) on the canvas, and holds information of every pixel inside that rectangle. For every pixel in an ImageData object there are four pieces of information, the RGBA values: R - The color red (from 0-255), G - The color green (from 0-255), B - The color blue (from 0-255), A - The alpha channel (from 0-255; 0 is transparent and 255 is fully visible). The color/alpha information is held in an array, and is stored in the data property of the ImageData object. Parameter values include:

x: the x coordinate (in pixels) of the upper-left corner to start copy from.

y: the y coordinate (in pixels) of the upper-left corner to start copy from.

width: the width of the rectangular area you will copy.

height: the height of the rectangular area you will copy.

Examples

code:
                <div class="spec">
                    <canvas id="method31" width="400" height="200" 
                    style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                    <button onclick="copy()">Copy</button>
                </div>
                <script>
                    var method31 = document.getElementById("method31");
                    var ctx_method31 = method31.getContext("2d");
                    ctx_method31.fillStyle = "red";
                    ctx_method31.fillRect(10, 10, 50, 50);
                    function copy() {
                    var imgData = ctx_method31.getImageData(10, 10, 50, 50);
                    ctx_method31.putImageData(imgData, 10, 70);
                    }
                </script>
            

putImageData()

The putImageData ()method puts the image data (from a specified ImageData object) back onto the canvas. Parameter values include:

imgData: specifies the ImageData object to put back onto the canvas.

x: the x-coordinate, in pixels, of the upper-left corner of the ImageData object.

y: the y-coordinate, in pixels, of the upper-left corner of the ImageData object.

dirtyX: optional. The horizontal (x) value, in pixels, where to place the image on the canvas.

dirtyY: optional. The vertical (y) value, in pixels, where to place the image on the canvas.

dirtyWidth: optional. The width to use to draw the image on the canvas.

dirtyHeight: optional. The height to use to draw the image on the canvas.

Examples

code:
                <div class=spec>
                    <canvas id="method32" width="400" height="200" 
                    style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                    <button onclick="copy_a()">Copy</button>
                </div>
                <script>
                    var method32 = document.getElementById("method32");
                    var ctx_method32 = method32.getContext("2d");
                    ctx_method32.fillStyle = "red";
                    ctx_method32.fillRect(10, 10, 50, 50);
                    function copy_a() {
                    var imgData = ctx_method32.getImageData(10, 10, 50, 50);
                    ctx_method32.putImageData(imgData, 10, 70);
                    }
                </script>
            

save()

The save()method saves the state of the current context.

restore()

The restore() method returns previously saved path state and attributes.

createEvent()

toDataURL()


colors, styles, and shadows in canvas

top

properties:

fillStyle: sets or returns the color, gradient, or pattern used to fill the drawing.

strokeStyle: sets or returns the color, gradient, or pattern used for strokes.

shadowColor: sets or returns the color to use for shadows.

shadowBlur: sets or returns the blur level for shadows.

shadowOffsetX: sets or returns the horizontal distance of the shadow from the shape.

shadowOffsetY: sets or returns the vertical distance of the shadow from the shape.

Examples

code:
                <div class="spec">
                    <canvas id="canvas_prop1" width="300" height="200" 
                    style="border-radius:1vw; border: 0.2vw solid black;"></canvas>
                </div>
                <script>
                    const prop1 = document.getElementById('canvas_prop1');
                    const ctx_prop1 = canvas_prop1.getContext('2d');
                    ctx_prop1.fillStyle = 'blue';
                    ctx_prop1.shadowBlur = 20;
                    ctx_prop1.shadowOffsetX = 20;
                    ctx_prop1.shadowColor = "green";
                    ctx_prop1.fillRect(20, 20, 200, 160);
                </script>
            

methods

createLinearGradient(): creates a linear gradient (to use on canvas content): x0, y0, x1, y1.

createPattern(): repeats a specified element in the specified direction: image, repeat, repeat-x, repeat-y, no-repeat .

createRadialGradient(): creates a radial/circular gradient (to use on canvas content): x0, y0, x1, y1, r1.

addColorStop(): specifies the colors and stop positions in a gradient object: stop, color.

Examples

code:
                <div class="spec">
                    <canvas id="canvas_meth1" width="300" height="200" 
                    style="border-radius: 1vw; border: 0.2vw solid black;"></canvas>
                </div>
                <script>
                    var meth1 = document.getElementById('canvas_meth1');
                    var ctx_meth1 = meth1.getContext('2d');
                    var grd_meth1 = ctx_meth1.createLinearGradient(0, 0, 170, 0);
                    grd_meth1.addColorStop(0, "black");
                    grd_meth1.addColorStop(1, "white");
                    ctx_meth1.fillStyle = grd_meth1;
                    ctx_meth1.fillRect(20, 20, 250, 150);
                </script>     
            

canvas line styles

top

properties

lineCap: sets or returns the style of the >end caps for a line: butt, round, or square.

lineJoin: sets or returns the type of corner created, when two lines meet: bevel, round or miter.

lineWidth: sets or returns the current line width: number.

miterLimit: sets or returns the maximum miter length: number.

Examples

code:
                <div class="spec">
                    <canvas id="canvas_line1" width="300" height="200" 
                    style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                </div>
                <script>
                    var line1 = document.getElementById("canvas_line1");
                    var ctx_line1 = line1.getContext("2d");
                    ctx_line1.lineWidth = 10;
                    ctx_line1.lineJoin = "miter";
                    ctx_line1.miterLimit = 5;
                    ctx_line1.moveTo(20, 20);
                    ctx_line1.lineTo(50, 27);
                    ctx_line1.lineTo(20, 34);
                    ctx_line1.stroke();
                </script>
            

rectangles

top

methods

rect(); creates a rectangle: x, y, width, height.

fillRect(): draws a "filled" rectangle:x, y, width, height.

strokeRect(): draws a rectangle (no fill): x, y, width, height.

clearRect(): Clears the specified pixels within a given rectangle:x, y, width, height.

Examples

code:
                <div class="spec">
                    <canvas id="canvas_rect" width="300" height="200" 
                    style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                </div>
                <script>
                    var rect = document.getElementById("canvas_rect");
                    var ctx_rect = rect.getContext("2d");
                    ctx_rect.fillStyle = "red";
                    ctx_rect.fillRect(0, 0, 300, 200);
                    ctx_rect.clearRect(20, 20, 100, 100);
                </script>
            

paths

top

methods

fill(): fills the current drawing (path): default is black.

stroke(): actually draws the path you have defined: default is black.

beginPath(): begins a path, or resets the current path.

moveTo(): moves the path to the specified point in the canvas, without creating a line: x, y.

closePath(): creates a path from the current point back to the starting point.

lineTo(): adds a new point and creates a line to that point from the last specified point in the canvas: x, y.

clip(): clips a region of any shape and size from the original canvas.

quadraticCurveTo(): creates a quadratic Bézier curve: cpx, cpy, x, y.

bezierCurveTo(): creates a cubic Bézier curve:cp1x, cp1y, cp2x, cp2y, x, y.

arc(): creates an arc/curve (used to create circles, or parts of circles)x, y, r, sAngle, eAngle, counterclockwise.

arcTo(): creates an arc/curve between two tangents: x1, y1, x2, y2, r.

isPointInPath(): returns true if the specified point is in the current path, otherwise false: x, y.

Examples

code:
                <div class="spec">
                    <canvas id="canvas_path" width="300" height="200" 
                    style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                </div>
                <script>
                    var path = document.getElementById("canvas_path");
                    var ctx_path = path.getContext("2d");
                    ctx_path.beginPath();
                    ctx_path.moveTo(20, 20);
                    ctx_path.bezierCurveTo(20, 150, 200, 150, 200, 20);
                    ctx_path.stroke();
                </script>
            
code:
                <div class=spec>
                    <canvas id="canvas_path1" width="300" height="300"></canvas>
                </div>
                <script>
                    let path1 = document.getElementById('canvas_path1');
                    if (canvas_path1.getContext) {
                        let ctx_path1 = canvas_path1.getContext('2d');
        
                        for (let i = 0; i < 4; i++) {
                            for (let j = 0; j < 3; j++) {
                                ctx_path1.beginPath();
                                let x = 65 + j * 70; // x coordinate
                                let y = 65 + i * 70; // y coordinate
                                let radius = 30; // Arc radius
                                let startAngle = 0; // Starting point on circle
                                let endAngle = Math.PI + (Math.PI * j) / 2; // End point on circle
                                let anticlockwise = i % 2 !== 0; // clockwise or anticlockwise
        
                                ctx_path1.arc(x, y, radius, startAngle, endAngle, anticlockwise);
        
                                if (i > 1) {
                                ctx_path1.fill();
                                } else {
                                ctx_path1.stroke();
                                }
                            }
                        }
                    }
                </script>
            

transformations

top

methods

scale(): scales the current drawing bigger or smaller: scalewidth, scaleheighht.

rotate(): rotates the current drawing: angle.

translate(): remaps the (0,0) position on the canvas: x, y.

transform(): replaces the current transformation matrix for the drawing: a (horizontal scaling), b (horizontal skewing), c (vertical skewing), d (vertical scaling), e (horizontal moving), f (vertical moving).

setTransform(): resets the current transform to the identity matrix. Then runs transform(): a (horizontal scaling), b (horizontal skewing), c (vertical skewing), d (vertical scaling), e (horizontal moving), f (vertical moving).

Examples

code:>
                <div class="spec">
                    <canvas id="canvas_trans" width="300" height="200" 
                    style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                </div>
                <script>
                    var trans = document.getElementById("canvas_trans");
                    var ctx_trans = trans.getContext("2d");
                    ctx_trans.fillStyle = "yellow";
                    ctx_trans.fillRect(0, 0, 250, 100)
        
                    ctx_trans.transform(1, 0.5, -0.5, 1, 30, 10);
                    ctx_trans.fillStyle = "red";
                    ctx_trans.fillRect(0, 0, 250, 100);
        
                    ctx_trans.transform(1, 0.5, -0.5, 1, 30, 10);
                    ctx_trans.fillStyle = "blue";
                    ctx_trans.fillRect(0, 0, 250, 100);
                </script>
            

Note: the transformation will only affect drawings made after the transform() method is called.


text

top

properties

font: sets or returns the current font properties for text content: font-style, font-variant, font-weight, font-size/line-height, font-family, etc.

textAlign: sets or returns the current alignment for text content: start, end, center, left, right.

textBaseline: sets or returns the current text baseline used when drawing text: alphabetic, top, hanging, middle, ideographic, bottom.

Examples

code:
                <div class="spec">
                    <canvas id="canvas_text" width="300" height="200" 
                    style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                </div>
                <script>
                    var text = document.getElementById("canvas_text");
                    var ctx_text = text.getContext("2d");
                    ctx_text.strokeStyle = "red";
                    ctx_text.moveTo(150, 20);
                    ctx_text.lineTo(150, 170);
                    ctx_text.stroke();
                    ctx_text.font = "15px Arial";
                    // Show the different textAlign values
                    ctx_text.textAlign = "start";
                    ctx_text.fillText("textAlign=start", 150, 60);
                    ctx_text.textAlign = "end";
                    ctx_text.fillText("textAlign=end", 150, 80);
                    ctx_text.textAlign = "left";
                    ctx_text.fillText("textAlign=left", 150, 100);
                    ctx_text.textAlign = "center";
                    ctx_text.fillText("textAlign=center", 150, 120);
                    ctx_text.textAlign = "right";
                    ctx_text.fillText("textAlign=right", 150, 140);
                </script>
            

methods

fillText(): draws "filled" text on the canvas: text, x, y, maxWidth.

strokeText(): draws text on the canvas (no fill): text, x, y, maxWidth.

measureText(): returns an object that contains the width of the specified text: text.

Examples

code:
                <div class="spec">
                    <canvas id="canvas_text1" width="300" height="200" 
                    style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                </div>
                <script>
                    var text1 = document.getElementById("canvas_text1");
                    var ctx_text1 = text1.getContext("2d");
                    ctx_text1.font = "20px Georgia";
                    ctx_text1.strokeText("Hello World!", 10, 50);
                    ctx_text1.font = "30px Verdana";
                    // Create gradient
                    var gradient_text1 = ctx_text1.createLinearGradient(0, 0, text1.width, 0);
                    gradient_text1.addColorStop("0", "magenta");
                    gradient_text1.addColorStop("0.5", "blue");
                    gradient_text1.addColorStop("1.0", "red");
                    // Fill with gradient
                    ctx_text1.strokeStyle = gradient_text1;
                    ctx_text1.strokeText("Big smile!", 10, 90);
                </script>
            

image drawing

top

methods

drawImage(): draws an image, canvas, or video onto the canvas: img, sx (optional), sy (optional), swidth (optional), sheight (optional), x, y, width, height.

Examples

Image to use:

Van Gogh

Canvas:

code:
                <div class="spec">
                    <p>Image to use:</p>
                    <img id="vangogh" src="../pics/vangogh.jpg" style="width:15vw; 
                    height: 15vw;" alt="Van Gogh">
                    <p>Canvas:</p>
                    <canvas id="canvas_beeld" width="300" height="200" 
                    style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                </div>
                <script>
                    window.onload = function() {
                        var beeld = document.getElementById("canvas_beeld");
                        var ctx_beeld = beeld.getContext("2d");
                        var img = document.getElementById("vangogh");
                        ctx_beeld.drawImage(img, 10, 10);
                    }
                </script>
            

pixel manipulation

top

properties

width: returns the width of an ImageData object.

height: returns the height of an ImageData object .

data: returns an object that contains image data of a specified ImageData object.

Examples

code:
                <div class="spec">
                    <canvas id="pix1" width="300" height="200" 
                    style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                </div>
                <script>
                    var pix1 = document.getElementById("pix1");
                    var ctx_pix1 = pix1.getContext("2d");
                    var imgData = ctx_pix1.createImageData(100, 100);
                    var i;
                    for (i = 0; i < imgData.data.length; i += 4) {
                    imgData.data[i + 0] = 255;
                    imgData.data[i + 1] = 0;
                    imgData.data[i + 2] = 0;
                    imgData.data[i + 3] = 255;
                    }
                    ctx_pix1.putImageData(imgData, 10, 10);
                </script>
            

methods

createImageData(): creates a new, blank ImageData object: width, height, imagedata.

getImageData(): returns an ImageData object that copies the pixel data for the specified rectangle on a canvas: x, y, width, height.

putImageData(): puts the image data (from a specified ImageData object) back onto the canvas: imgData, x, y, dirtyX (optional), dirtyY (optional), dirtyWidth (optional), dirtyHeight (optional).

Examples

code:
                <div class="spec">
                    <canvas id="pix2" width="300" height="200" 
                    style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                    <button onclick="copyData()">Copy</button>
                </div>
                <script>
                    var pix2 = document.getElementById("pix2");
                    var ctx_pix2 = pix2.getContext("2d");
                    ctx_pix2.fillStyle = "red";
                    ctx_pix2.fillRect(10, 10, 50, 50);
        
                    function copyData() {
                    var imgData = ctx_pix2.getImageData(10, 10, 50, 50);
                    ctx_pix2.putImageData(imgData, 10, 70);
                    }
                </script>
            

compositing

top

properties

globalAlpha: sets or returns the current alpha or transparency value of the drawing: number.

globalCompositeOperation: sets or returns how a new image are drawn onto an existing image: source-over, source-atop, source-in, source-out, destination-over, destination-atop, destination-in, destination-out, lighter, copy, xor.

Examples

code:
                <div class="spec">
                    <canvas id="comp" width="300" height="200" 
                    style="border-radius: 1vw; border: 0.2vw solid black;"></canvas> 
                </div>
                <script>
                    var comp = document.getElementById("comp");
                    var ctx_comp = comp.getContext("2d");
                    ctx_comp.fillStyle = "red";
                    ctx_comp.fillRect(20, 20, 75, 50);
                    // Turn transparency on
                    ctx_comp.globalAlpha = 0.2;
                    ctx_comp.fillStyle = "blue";
                    ctx_comp.fillRect(50, 50, 75, 50);
                    ctx_comp.fillStyle = "green";
                    ctx_comp.fillRect(80, 80, 75, 50);
                </script>
            

canvas examples

top

some examples

examples

Example 0

Codes:

                    <div class="spec">
                        <canvas id="canvas_08" style="width:30vw; height:20vw"></canvas>
                    </div>
                    <script>
                        function got_08() {
                            let ctx_08 = document.getElementById('canvas_08').getContext('2d');
                            for (var i = 0; i < 9; i++) {
                                for (var j = 0; j < 9; j++) {
                                ctx_08.fillStyle = 'rgb(' + Math.floor(255 - 42.5 * i) + ', ' +  Math.floor(255 - 42.5 * j) + ', 0)';
                                ctx_08.fillRect(j * 30, i * 30, 40, 40);
                                }
                            }
                        }
                        got_08()  
                    </script>
                

Example 1

Codes:

                    <div class="spec">
                        <canvas id="canvas_18" style="width:30vw; height:20vw"></canvas>
                    </div>
                    <script>
                    function got_18() {
                            let ctx_18 = document.getElementById('canvas_18').getContext('2d');
                            for (let i = 0; i < 9; i++) {
                                for (let j = 0; j < 9; j++) {
                                    ctx_18.strokeStyle = 'rgb(0, ' + Math.floor(255 - 142.5 * i) + ', ' + 
                                                    Math.floor(255 - 142.5 * j) + ')';
                                    ctx_18.beginPath();
                                    ctx_18.arc(12.5 + j * 40, 12.5 + i * 40, 10, 0, Math.PI * 2, true);
                                    ctx_18.stroke();
                                }
                            }
                        }
                        got_18();
                    </script>
                

Example 2

Codes:

                    <div class="spec">
                        <canvas id="canvas_28" style="width:30vw; height:20vw"></canvas>
                </div>
                <script>
                        function got_28() {
                            const ctx_28 = document.getElementById('canvas_28').getContext('2d');
                                // draw background
                                ctx_28.fillStyle = '#FD0';
                                ctx_28.fillRect(0, 0, 120, 100);
                                ctx_28.fillStyle = '#6C0';
                                ctx_28.fillRect(120, 0, 120, 100);
                                ctx_28.fillStyle = '#09F';
                                ctx_28.fillRect(0, 100, 120, 120);
                                ctx_28.fillStyle = '#F30';
                                ctx_28.fillRect(120, 100, 120, 120);
                                ctx_28.fillStyle = '#FFF';
                                // set transparency value
                                ctx_28.globalAlpha = 0.3;
                                // Draw semi transparent circles
                                for (var i = 0; i < 9; i++) {
                                    ctx_28.beginPath();
                                    ctx_28.arc(110, 90, 10 + 10 * i, 0, Math.PI * 2, true);
                                    ctx_28.fillStyle = 'orange';
                                    ctx_28.fill();
                                }
                        }
                        got_28();
                </script>
            

Example 3

Codes:

                    <div class="spec">
                        <canvas id="canvas_38" style="width:30vw; height:20vw"></canvas>
                    </div>
                    <script>
                        function got_38() {
                            let ctx_38 = document.getElementById('canvas_38').getContext('2d');
                        // Draw background
                            ctx_38.fillStyle = 'rgb(255, 221, 0)';
                            ctx_38.fillRect(0, 0, 300, 80);
                            ctx_38.fillStyle = 'rgb(102, 204, 0)';
                            ctx_38.fillRect(0, 80, 300, 80);
                            ctx_38.fillStyle = 'rgb(0, 153, 255)';
                            ctx_38.fillRect(0, 160, 300, 80);
                            ctx_38.fillStyle = 'rgb(255, 51, 0)';
                            ctx_38.fillRect(0, 240, 300, 80);
            
                            // Draw semi transparent rectangles
                            for (let i = 0; i < 12; i++) {
                                ctx_38.fillStyle = 'rgba(255, 255, 255, ' + (i + 1) / 10 + ')';
                                for (let j = 0; j < 6; j++) {
                                ctx_38.fillRect(5 + i * 25, 5 + j * 80, 18, 60);
                                }
                            }
                        }
                        got_38();
                    </script>
                

Example 4

Codes:

                    <div class="spec">
                        <canvas id="canvas_48" style="width:30vw; height:20vw"></canvas>
                    </div>
                    <script>
                        function got_48() {
                            const ctx_48 = document.getElementById('canvas_48').getContext('2d');
                            for (var i = 0; i < 14; i++) {
                                ctx_48.lineWidth = 2 + i;
                                ctx_48.beginPath();
                                ctx_48.moveTo(9 + i * 21, 10);
                                ctx_48.lineTo(9 + i * 21, 240);
                                ctx_48.stroke();
                            }
                        }
                        got_48();
                    </script>
                

Example 5

Codes:

                    <div class="spec">
                        <canvas id="canvas_58" style="width:30vw; height:20vw"></canvas>
                    </div>
                    <script>
                        function got_58() {
                            const ctx_58 = document.getElementById('canvas_58').getContext('2d');
                            const lineCap = ['butt', 'round', 'square'];
                            // Draw guides
                            ctx_58.strokeStyle = "silver";
                            ctx_58.beginPath();
                            ctx_58.moveTo(10, 10);
                            ctx_58.lineTo(290, 10);
                            ctx_58.moveTo(10, 240);
                            ctx_58.lineTo(140, 240);
                            ctx_58.stroke();
                            // Draw lines
                            ctx_58.strokeStyle = 'orange';
                            for (var i = 0; i < lineCap.length; i++) {
                                ctx_58.lineWidth = 20;
                                ctx_58.lineCap = lineCap[i];
                                ctx_58.beginPath();
                                ctx_58.moveTo(25 + i * 50, 10);
                                ctx_58.lineTo(25 + i * 50, 240);
                                ctx_58.stroke();
                            }
                        }
                        got_58();
                    </script>
                

Example 6

Codes:

                    <div class="spec">
                        <canvas id="canvas_68" style="width:30vw; height:20vw"></canvas>
                    </div>
                    <script>
                    function got_68() {
                        const ctx_68 = document.getElementById('canvas_68').getContext('2d');
                        const lineJoin = ['round', 'bevel', 'miter'];
                        ctx_68.lineWidth = 10;
                        for (let i = 0; i < lineJoin.length; i++) {
                            ctx_68.lineJoin = lineJoin[i];
                            ctx_68.beginPath();
                            ctx_68.moveTo(-5, 5 + i * 40);
                            ctx_68.lineTo(75, 45 + i * 40);
                            ctx_68.lineTo(150, 5 + i * 40);
                            ctx_68.lineTo(225, 45 + i * 40);
                            ctx_68.lineTo(300, 5 + i * 40);
                            ctx_68.stroke();
                        }
                    }
                    got_68();
                    </script>
                

Example 7

Codes:

                    <div class="spec">
                        <canvas id="canvas_78" style="width:30vw; height:20vw"></canvas>
                    </div>
                    <script>
                    function got_78() {
                        const ctx_78 = document.getElementById('canvas_78').getContext('2d');
                        // Create gradients
                        let radgrad = ctx_78.createRadialGradient(45, 45, 10, 52, 50, 30);
                        radgrad.addColorStop(0, '#A7D30C');
                        radgrad.addColorStop(0.9, '#019F62');
                        radgrad.addColorStop(1, 'rgba(1, 159, 98, 0)');
                        
                        let radgrad2 = ctx_78.createRadialGradient(105, 105, 20, 112, 120, 50);
                        radgrad2.addColorStop(0, '#FF5F98');
                        radgrad2.addColorStop(0.75, '#FF0188');
                        radgrad2.addColorStop(1, 'rgba(255, 1, 136, 0)');
            
                        let radgrad3 = ctx_78.createRadialGradient(95, 15, 15, 102, 20, 40);
                        radgrad3.addColorStop(0, '#00C9FF');
                        radgrad3.addColorStop(0.8, '#00B5E2');
                        radgrad3.addColorStop(1, 'rgba(0, 201, 255, 0)');
            
                        let radgrad4 = ctx_78.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_78.fillStyle = radgrad4;
                        ctx_78.fillRect(0, 0, 250, 250);
                        ctx_78.fillStyle = radgrad3;
                        ctx_78.fillRect(0, 0, 250, 250);
                        ctx_78.fillStyle = radgrad2;
                        ctx_78.fillRect(0, 0, 250, 250);
                        ctx_78.fillStyle = radgrad;
                        ctx_78.fillRect(0, 0, 250, 250);
                    }
                    got_78();
                    
                

Example 8

Codes:

                    <div class=spec>
                        <canvas id="canvas_88" style="width:30vw; height:20vw"></canvas>
                    </div>
                    <script>
                    function got_88() {
                            let canvas_88 = document.getElementById('canvas_88');
                            if (canvas_88.getContext) {
                                let ctx_88 = canvas_88.getContext('2d');
                                // Quadratric curves example
                                ctx_88.beginPath();
                                ctx_88.moveTo(175, 125);
                                ctx_88.quadraticCurveTo(125, 125, 125, 162.5);
                                ctx_88.quadraticCurveTo(125, 200, 150, 200);
                                ctx_88.quadraticCurveTo(150, 220, 130, 225);
                                ctx_88.quadraticCurveTo(160, 220, 165, 200);
                                ctx_88.quadraticCurveTo(225, 200, 225, 162.5);
                                ctx_88.quadraticCurveTo(225, 125, 175, 125);
                                ctx_88.stroke();
                            }
                            }
                            got_88();
                    </script>