The Wayback Machine - https://web.archive.org/web/20240930163649/https://www.geeksforgeeks.org/html-canvas-basics/
Open In App

HTML Canvas Basics

Last Updated : 06 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will know HTML Canvas Basics, and their implementation through the examples. 

The HTML “canvas” element is used to draw graphics via JavaScript. The “canvas” element is only a container for graphics. One must use JavaScript to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and adding images. The canvas would be a rectangular area on an HTML page. By default, a canvas has no border and no content.

Syntax:

<canvas>
    Content...
</canvas>

It is recommended to have 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.

Supported Properties: The properties like Colors, Styles, Shadows, Line Styles, Rectangles, Paths, Transformations, Text, Pixel Manipulation, Compositing & Image Drawing, are the global attributes that are supported by all the canvas tags. Please refer to the HTML Canvas Complete Reference article for the details.

Example 1: This example illustrates the use of canvas with a linear gradient & stroke-style text in HTML.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <canvas id="gfg" 
            width="300px" 
            height="100px" 
            style="border:1px solid #d3d3d3;">
    </canvas>
    <script>
        let g = document.getElementById("gfg");
        let geeks = g.getContext("2d");
        let gradient = geeks.createLinearGradient(1, 4, g.width, 2);
        gradient.addColorStop("0", "green");
        gradient.addColorStop("0.4", "yellow");
        gradient.addColorStop("1.0", "aqua");
        geeks.font = "40px sans-serif";
        geeks.fillStyle = "red";
        geeks.strokeStyle = gradient;
        geeks.strokeText("GeeksforGeeks", 10, 60);
    </script>
</body>
  
</html>


Output:

HTML canvas with a linear gradient

Example 2: The following code demonstrates the empty canvas.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <canvas id="myCanvas" 
            width="400" 
            height="200" 
            style="border:2px solid #000000;"> 
    </canvas>
</body>
  
</html>


Output:

HTML empty canvas

There are various shapes that can be possible to draw using Canvas, which are discussed below.

Example 1: This example shows the HTML Canvas to draw a circle.

HTML




<!DOCTYPE html>
<html>
<head>
    <title>Circle Drawing</title>
</head>
<body>
    <canvas id="GFG" width="400" height="200" style="border:2px solid #d3d3d3;"></canvas>
    <script>
         
        let g = document.getElementById("GFG");
        let geeks = g.getContext("2d");
        geeks.beginPath();
        geeks.arc(200, 100, 50, 0, 2 * Math.PI);
        geeks.stroke();
    </script>
</body>
</html>


Output:

Drawing Circle with HTML Canvas

Example 2: In this example, we will write a text using HTML Canvas.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <canvas id="GFG" 
            width="600" 
            height="200" 
            style="border:1px solid #d3d3d3;"> 
    </canvas>
    <script>
        let g = document.getElementById("GFG");
        let geeks = g.getContext("2d");
        geeks.font = "30px Arial";
        geeks.fillText("GeeksForGeeks", 170, 50);
    </script>
</body>
  
</html>


Output:

Screenshot-2023-07-18-104933

Writing text with HTML Canvas

Example 3: This example illustrates the use of linear-gradient property in HTML Canvas.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <canvas id="GFG" 
            width="400" 
            height="200" 
            style="border:2px solid #d3d3d3;"> 
    </canvas>
    <script>
        let G = document.getElementById("GFG");
        let geeks = G.getContext("2d");
        let grd = geeks.createLinearGradient(0, 0, 200, 0);
        grd.addColorStop(0, "yellow");
        grd.addColorStop(1, "grey");
        geeks.fillStyle = grd;
        geeks.fillRect(50, 50, 300, 80);
    </script>
</body>
  
</html>


Output:

HTML Canvas with linear-gradient

Example 4: In this example, we will draw the image by using the <canvas> tag.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <p>Image to use:</p>
    <img id="image" 
         src=
         alt="GeeksforGeeks logo" 
         width="250" 
         height="200">
      
    <p>Canvas to fill:</p>
    <canvas id="gfg" 
            width="300" 
            height="300" 
            style="border:1px solid #d3d3d3; "> 
    </canvas>
      
    <p>
        <button onclick="gfg()">
          Click to Try
          </button>
    </p>
    <script>
    function gfg() {
        let g = document.getElementById("gfg");
        let geeks = g.getContext("2d");
        let img = document.getElementById("image");
        geeks.drawImage(img, 0, 0);
    }
    </script>
</body>
  
</html>


Output:

Drawing image with tag

Example 5: This example demonstrates the use of the Shadow blur property in HTML Canvas.

HTML




<!DOCTYPE html>
<html>
<body>
    <canvas id="GFG" 
            width="500" 
            height="250" ;> 
      </canvas>
    <script>
        let g = document.getElementById("GFG");
        let geeks = g.getContext("2d");
        geeks.shadowBlur = 20;
        geeks.shadowColor = "yellow";
        geeks.fillStyle = "red";
        geeks.fillRect(30, 20, 100, 80);
    </script>
</body>
</html>


Output:

HTML Canvas with Shadow blur property

Example 6: In this example, we will use rotate() method in the HTML Canvas.

HTML




<!DOCTYPE html>
<html>
<body>
    <canvas id="GFG" 
            width="300" 
            height="150;">
    </canvas>
    <script>
        let g = document.getElementById("GFG");
        let geeks = g.getContext("2d");
        geeks.rotate(20 * Math.PI / 180);
        geeks.fillRect(100, 20, 100, 50);
    </script>
</body>
</html>


Output:

HTML Canvas with rotate() method

Example 7: In this example, we have used the translate() method to remap the (0,0) position on the canvas.

HTML




<!DOCTYPE html>
<html>
<body>
    <canvas id="GFG" 
            width="300" 
            height="150;">
      </canvas>
    <script>
        let g = document.getElementById("GFG");
        let geeks = g.getContext("2d");
        geeks.fillRect(10, 10, 100, 50);
        geeks.translate(80, 90);
        geeks.fillRect(10, 10, 100, 50);
    </script>
</body>
</html>


Output:

HTML Canvas with translate() method

Example 8: This example illustrates the use of the transform() method in HTML Canvas.

HTML




<!DOCTYPE html>
<html>
<body>
    <canvas id="GFG" 
            width="300" 
            height="150;">
    </canvas>
    <script>
        let g = document.getElementById("GFG");
        let geeks = g.getContext("2d");
        geeks.fillStyle = "yellow";
        geeks.fillRect(0, 0, 250, 100)
        geeks.transform(1, 0.5, -0.5, 1, 30, 10);
        geeks.fillStyle = "grey";
        geeks.fillRect(0, 0, 250, 100);
        geeks.transform(1, 0.5, -0.5, 1, 30, 10);
        geeks.fillStyle = "black";
        geeks.fillRect(0, 0, 250, 100);
    </script>
</body>
</html>


Output:

HTML Canvas with transform() method

Creating Animation in HTML Canvas: JavaScript helps to simulate good animation over an HTML5 canvas. Two important JavaScript methods which can be used to animate an image on a canvas:

  1. setInterval(callback, time): This method repeatedly executes the supplied code after a given time.
  2. setTimeout(callback, time): This method executes the supplied code only once after a given time.

Supported Browser:

  • Google Chrome 93.0
  • Microsoft Edge 93.0
  • IE 11.0
  • Firefox 92.0
  • Opera 78.0
  • Safari 14.1


Previous Article
Next Article

Similar Reads

HTML Course Basics of HTML
In this article, we will go through all the basic stuff required to write HTML. There are various tags that we must consider and know about while starting to code in HTML. These tags help in the organization and basic formatting of elements in our script or web pages. These step-by-step procedures will guide you through the process of writing HTML.
5 min read
How to resize an image in an HTML 5 canvas ?
The canvas element is part of HTML 5 and it allows the rendering of 2D shapes and bitmap(also called "raster") images. A canvas actually has two sizes: the size of the element. the size of the element's drawing surface. The element's width and height attributes set both the size of the element and the size of the element's drawing surface. CSS attr
1 min read
HTML canvas lineWidth Property
The HTML canvas lineWidth property is used to set or return the width of the line (thickness of the line). The width of the line is set in terms of pixels. The default value of this property is 1. Syntax: context.lineWidth = number; Property Values: number: This property value indicates the number which specifies the line width in terms of pixels.
2 min read
HTML canvas textAlign Property
The HTML canvas textAlign Property is used to set or return the current alignment for text content, according to the anchor point. Basically, the text will start at that position and the text will end at that specified position. Syntax: context.textAlign="center | end | left | right | start"; Property Values: start: It has a Default. The text start
2 min read
HTML canvas font Property
The HTML canvas font Property is used to change the present font family of the Text content of the <canvas> element. The font Property has a Default Property i.e 10px sans-serif Syntax: context.font="italic small-caps bold 12px arial"; Property Values: font-family: It is used to set the font type of an HTML element. It holds several font name
2 min read
HTML canvas lineJoin Property
The HTML canvas lineJoin property is used to set or return the type of corner created, when two lines meet, by using the lineJoin property. The type of join can have one of three styles: bevel, round, or miter. However, the join style has generally miter style. Syntax: context.lineJoin = "bevel|round|miter"; Property Values: miter: It is the defaul
2 min read
HTML DOM Canvas Object
The DOM Canvas Object is used to represent the HTML <Canvas> element. The <canvas> tag is used to draw graphics in the document using javascript. It is new in HTML5. The canvas element is accessed by getElementById(). Syntax: accessed by getElementById("id"). Where “id” is the ID assigned to the Canvas tag. Example 1: In this example, w
2 min read
HTML Canvas Draw Bezier Curve
Curves on HTML canvas can be drawn using arcs, but drawing a complex diagram using arcs is quite a tedious task. In the given circumstance, Bezier curve will be very useful in providing more flexibility in drawing curves. Bezier curves on HTML canvas are drawn using a start point, one or more control point/points and an endpoint. Example: In the ca
4 min read
How to get Pixel from HTML Canvas ?
To get the pixel of any specific portion from the HTML canvas you can use the HTML canvas getImageData() Method. The getImageData() method usually returns an ImageData object that contains the pixel information of the specified object on the HTML canvas. Example 1: This example will display each pixel value of the square box. The boxes color is lin
3 min read
HTML canvas shadowColor Property
The Canvas shadowColor property is used to set or returns the color that is used for shadows. The fillStyle property is used to create shadows. This property can be set to a string representing a CSS color value, which we want as shadow color. By default, shadow color is set to black (CSS color value #000000). Syntax:: context.shadowColor = color;
2 min read
HTML canvas rect() Method
The rect() method in HTML is used to create a rectangle in HTML. Syntax: context.rect(x, y, width, height) Parameters: x: It stores the x-coordinate of the top-left corner of the rectangle.y: It stores the y-coordinate of the top-left corner of the rectangle.width: It stores the width in pixel.height: It stores the height in pixel. Example-1: C/C++
1 min read
HTML canvas fillStyle Property
The canvas fillStyle property is used to set or return the color, gradient, or pattern used to fill the drawing. Style: context.fillStyle=color|gradient|pattern; Property Value: color: It is used to set the filled color of the drawing. The default value of the canvas fillStyle property is black.gradient: It is used to set the gradient object to fil
2 min read
HTML canvas strokeStyle Property
The canvas strokeStyle property is used to set or return the stroke of color, gradient, or pattern used in the drawing. Syntax: context.strokeStyle=color|gradient|pattern; Property Value: color: It is used to set the filled color of drawing. The default value of canvas fillStyle property is black.gradient: It is used to set the gradient object to f
2 min read
HTML canvas clearRect() Method
The clearRect() method is used to clear the specified pixels within a given rectangle. Syntax: context.clearRect( x, y, width, height ) Parameters: x: It stores the x-coordinate of the top-left corner of the rectangle.y: It stores the y-coordinate of the top-left corner of the rectangle.width: It stores the width in pixel.height: It stores the heig
1 min read
HTML canvas strokeRect() Method
The strokeRect() method is used to draw the rectangle in a given color. The default color of the stroke is black. Syntax: context.strokeRect(x, y, width, height) Parameters: x: It stores the x-coordinate of the top-left corner of the rectangle.y: It stores the y-coordinate of the top-left corner of the rectangle.width: It stores the width in pixels
1 min read
HTML canvas fillRect() Method
The fillRect() method is used to fill the rectangle using the given color. The default color of the fillRect() method is black. Syntax: context.fillRect( x, y, width, height ) Parameters: This method accepts four parameters as mentioned above and described below: x: It stores the x-coordinate of top-left corner of rectangle.y: It stores the y-coord
1 min read
HTML canvas shadowBlur Property
The canvas shadowBlur property is used to set or return the blur level for shadows. Syntax: context.shadowBlur=number Property: number: It is used to set the blur level for the shadow. Example 1: C/C++ Code &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt; HTML canvas shadowBlur Property &lt;/title
1 min read
HTML canvas shadowOffsetX Property
The canvas shadowOffsetX property is used to set or return the horizontal distance of the shadow from the shape. This property holds a positive or negative value where a positive value indicates the shadow to the right and negative value indicates the shadow to the left. Syntax: context.shadowOffsetX=number Property Values: number: It is used to se
1 min read
HTML canvas fill() Method
The canvas fill() Method is used to fill the current drawing path. The default color of the canvas fill() method is black. Syntax: context.fill() Example-1: C/C++ Code <!DOCTYPE html> <html> <head> <title> HTML canvas fill() Method </title> </head> <body> <canvas id="GFG" width="500"
1 min read
HTML canvas stroke() Method
The canvas stroke() method is used to draw the path you have defined with all those moveTo() and lineTo() methods. The default color of the canvas stroke() method is black. Syntax: context.stroke() Example-1: C/C++ Code <!DOCTYPE html> <html> <head> <title> HTML canvas stroke() Method </title> </head> <body
1 min read
HTML <canvas> width Attribute
The HTML <canvas> width Attribute is used to specify the width of the <canvas> in terms of pixels. Syntax: <canvas width="pixels"> Attribute Values: It contains the value i.e pixels which specify the width of the canvas in terms of pixel. It has a Default value which is 300. Example: This Example illustrates the use of width attri
1 min read
HTML <canvas> height Attribute
The HTML <canvas> height Attribute is used to specify the height of the <canvas> element in terms of pixels. Syntax: <canvas height="pixels"> Attribute Values: It contains single value pixels which specify the height of the canvas in terms of pixel. It has a Default value which is 150. Example: This example illustrates the use of
1 min read
HTML canvas translate() Method
The HTML canvas translate() Method is used to specify that the object is translated by given translate amount. Syntax: context.translate(x, y) Parameter Values: x: It stores the value, that how much the canvas will move left or right means x-axis wise.y: It stores the value, that how much the canvas will move up and down means y-axis wise. Example
2 min read
HTML canvas rotate() Method
The HTML canvas rotate() Method is used to rotate the drawing by a given angle. Note that the rotation will only work on the canvas that was made after the rotation was done. Syntax: context.rotate(angle) Parameter Values: angle: It stores the rotation angle in radians. If the angle is given in the form of a degree then it converts into a radian by
1 min read
HTML canvas scale() Method
The HTML canvas scale() Method is used to scale the current drawing into smaller or larger size. After scaling the drawing, all the feature of drawing scaled. It will have to define before the canvas. Syntax: context.scale( scalewidth, scaleheight ) Parameter Values: scalewidth: It scale the width of current drawing, (1=100%, 0.5=50%, 2=200%, and s
2 min read
HTML canvas createLinearGradient() Method
The HTML Canvas createLinearGradient() method is used to create a linear gradient object. The gradient can be used to fill different colors in rectangles, circles, lines, text, etc. We can then assign the gradient color to the strokeStyle or fillStyle properties to fill or draw shapes such as rectangles, circles, lines, text, etc. The addColorStop(
2 min read
How to save an HTML 5 Canvas as an image on the server ?
Saving HTML canvas as an image is pretty easy, it can be done by just right-clicking on the canvas and save it as an image. But saving canvas as an image on the server is quite different. This article will show you how to achieve that. Sometimes it is required to save canvas image after doing some server processing and this article will help in sen
3 min read
HTML canvas lineCap Property
The canvas lineCap property is used to set or return the style of end caps of line. The line can have one of three cap styles: butt, round, or square. The default value of canvas lineCap property are butt. The lineCap property must be set before calling the stroke() function. Syntax: context.lineCap = "butt|round|square"; Property Values: butt: It
2 min read
HTML canvas beginPath() Method
The canvas beginPath() method is used to start a path or reset the current path. The moveTo(), lineTo(), quadricCurveTo(), bezierCurveTo(), arcTo(), and arc() methods are used to create paths. Also, the stroke() method is used to draw the path on the canvas. Syntax: context.beginPath(); Example 1: <!DOCTYPE html> <html> <head>
2 min read
HTML canvas quadraticCurveTo() Method
The canvas quadraticCurveTo() Method is used to create a quadratic curve on the canvas. The method adds a point to the current path by using the specified control points that represent the quadratic parametric curve. Syntax: context.quadraticCurveTo( cx, cy, x, y ); Parameters: cx: This parameter holds the x-coordinate of the quadratic control poin
2 min read