Notice: Undefined variable: user_id in /home/thetexvn/domains/thetexvn.com/public_html/blogs/follow.php on line 40
Getting Started with Canvas in HTML5 for Beginners | by Zia | TEXVN

Conversation

Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!

Join the discussion and share your insights now!

Comments 0


advertisement

Getting Started with Canvas in HTML5 for Beginners

Canvas in HTML5


Canvas is one of the most interesting features added to HTML5. The <canvas> element supports advanced graphics and interactions in many forms. In earlier versions of HTML, you could achieve this by using plug-ins. Using the <canvas> element eliminates the requirement for such plug-ins and makes working with graphics easier and more efficient. The <canvas> element is a drawing area where the user can draw graphics, use images, add animations, and also add text to enhance the user experience on Web pages.


Canvas element

The <canvas> element in HTML5 can be used to draw much more than just rectangles on websites. It can be used to dynamically draw graphics using JavaScript. This improves the overall performance of websites and avoids the requirement to download images from sites. The <canvas> element is represented like a rectangle on a page and allows the user to draw arcs, text, shapes, gradients, and patterns. By using <canvas>, the user can draw many complex shapes and also apply various effects and transformations.

The <canvas> in HTML5 is similar to the <div>, <table>, or <a> tag except that the content used in it is rendered through JavaScript.

The <canvas> element is simple and easy to use in JavaScript. The <canvas> element does not contain any drawing abilities, instead, the drawing is done using JavaScript code. To make use of the <canvas> element, a user has to add the <canvas> tag to the HTML page.

The use of <canvas> element.

<html>
<head>
 <style>
  canvas {border: 1px double red; margin: 4px}
 </style>
</head>
<body>
 <canvas width="278" height="200"></canvas>
</body>
</html>

In the code, the <style> element is used to display the border of the <canvas> element. The height and width attributes specify the size of the <canvas> element on the page.

To draw a <canvas> element, the user can use a context object. The context object contains drawing functions for a specific style of graphic. Two-dimensional (2D) context is used to work with 2D operations.

The <canvas> element in the DOM exposes the HTMLCanvasElement interface. This interface provides methods and properties for changing the presentation and layout of canvas elements. The HTMLCanvasElement has a getContext (context) method that returns the drawing context for the canvas.

The 2D context object for the canvas.

<html>
<head>
    <script>
      window.onload = function () {
        var canvas = document.getElementById('mCanvas');
        var ctext = canvas.getContext('2d');
        ctext.beginPath();
        ctext.rect(18, 50, 200, 100);
        ctext.fillStyle = "DarkBlue";
        ctext.fill();
      }
    </script>
</head>
<body>
    <canvas id="mCanvas" width="578" height="200"></canvas>
</body>
</html>

In the code, the height and width attributes define the height and width of the canvas element respectively. In the initializer function, the DOM object is accessed through the ID attribute and gets a 2D context by using the getContext() method. Here, the rectangle is created by using the rect (18, 50, 200, 100) method with x, y, height, and width parameters and is positioned at the left corner of the page.



Drawing a Line on Canvas

You can create lines on a canvas using the stroke (), beginPath (), lineTo(), and moveTo() methods.

Following is the syntax to create a canvas line:

Syntax:

  • ctext.beginPath () ;
  • ctext.moveTo (x, y) ;
  • ctext.lineTo (x, y) ;
  • ctext. stroke ()


where,

  • ctext - specifies a context object
  • beginPath () - Specifies a new drawing path
  • moveTo () - Specifies the creation of a new sub-path to the
  • line To () - Specifies the drawing of a line from the context position to the given position
  • stroke () - Specifies how to assign a color to the line and display it


Creating a line in HTML5 canvas.

<html>
<head>
    <title>Canvas Line</title>
    <script>
       window.onload = function () {
          var canvas = document.getElementById("mCanvas");
          var ctext = canvas.getContext("2d");
          ctext.beginPath();
          ctext.moveTo(100, 150);
          ctext.lineTo(50, 250);
          ctext.lineWidth = 5;
          ctext.strokeStyle = "blue";
          ctext.stroke();
       }
    </script>
</head>
<body>
    <canvas id="mCanvas" width="360" height="200"></canvas>
</body>
</html>

In the code, the height and width attributes are defined. The initializer function has the DOM object which is accessed through the ID attribute and gets a 2D context by using the getContext() method.

The beginPath() method is called through the context object to draw the path of the line The moveTo (100, 150) method is called that creates a new path for the given point to place the drawing cure This method moves the position of the window to the upper-left corner by giving the x and y coordinates Th lineTo (250, 50) method is called to draw the line from the context point to the given point Th lineWidth property is specified as 5 to define the width of the line on the canvas. The strokes property sets the color of the line to blue. The stroke () method assigns color to the line.



Working with Drawing Objects in Canvas

HTML5 canvas allows the user to work with different types of drawing objects. The following objects can be drawn on a canvas element:

1. Rectangle:

With HTML5 canvas, the user can create a rectangle using the rect () method. The HTML5 canvas is placed using the x and y parameters and appropriately sized through height and width properties. There is a collection of methods and properties that are used to draw different types of shapes.

Lists common properties and methods of various shapes.

  1. fillstyle: The values can be gradients, patterns, or CSS colors. The default property style is solid black, but the user can set the color according to requirements.
  2. fillRect (x, y, width, height): This enables the user to draw a rectangle with the existing fill style.
  3. strokeStyle(): The values can be gradients, patterns, or a CSS color.
  4. strokeRect (x, y, width, height): This enables the user to draw a rectangle with the existing stroke style. This property is used to draw the edges of the rectangle.
  5. clearRect (x, y, width, height): Used to clear the pixels in a rectangle.


How to create a rectangle in HTML5 canvas?

<html>
<head>
    <title>Canvas Rectangle</title>
    <script>
      window.onload = function () {
         var canvas = document.getElementById('mCanvas');
         var ctext = canvas.getContext('2d');
         ctext.beginPath();
         ctext.rect(30, 50, 150, 100);
         ctext.fillStyle = "Magenta";
         ctext.fill();
         ctext.lineWidth = 5;
         ctext.strokeStyle = 'black';
         ctext.stroke();
      }
    </script>
</head>
<body>
    <canvas id="mCanvas" width="360" height="200"></canvas>
</body>
</html>

In the code, the height and width attributes are defined. The initializer function has the DOM object which is accessed through the ID attribute and gets a 2D context by using the getContext() method. The beginPath() method is called through the context object to draw the rectangle. The rect (30, 50, 150, 100) method takes x, y, height, and width as parameters. The fillStyle property fills the rectangle with a magenta color. The fill() method is used to paint the rectangle. The linewidth property is specified as 5 to define the width of the line on the canvas. The strokeStyle property sets the stroke style of the rectangle to black. The stroke () method assigns color to the rectangle.


2. Arcs:

With HTML5 canvas, the user can create an arc by using the arc() method. Arcs are represented using a start angle, an end angle, a radius, a center point, and the drawing direction (anticlockwise or clockwise).

The syntax to draw an arc in HTML5 is as follows:

Syntax:

arc (x, y, radius, startAngle, endAngle, anticlockwise)

Where,

  1. x, y - Specifies the coordinates of the center of an arc
  2. Radius - Specifies the distance from the center to any point in the circle
  3. StartAngle, endAngle - Specifies the start and end points in the arc
  4. anticlockwise - Draws the arc clockwise or anticlockwise and accepts a boolean value


How to create an arc in HTML5 canvas?

<html>
<head>
    <title>Canvas Arc</title>
    <script>
      window.onload = function () {
         var canvas = document.getElementById("mCanvas");
         var ctext = canvas.getContext("2d");
         var x = canvas.width / 2;
         var y = canvas.height / 2;
         var radius = 75;
         var startAngle = 1.1 * Math.PI;
         var endAngle = 1.9 * Math.PI;
         var ctrClockwise = false;
         ctext.beginPath();
         ctext.arc(x, y, radius, startAngle, endAngle, ctrClockwise);
         ctext.lineWidth = 25;
         ctext.strokeStyle = "DarkGreen";
         ctext.stroke();
      }
    </script>
</head>
<body>
    <canvas id="mCanvas" width="278" height="250"></canvas>
</body>
</html>

In the code, the beginPath () method is called through the context object to draw an arc by using the arc () method which has x, y, and radius as parameters. The x and y are the coordinates of the circle, the radius is the distance from the center to draw the arc on the canvas. The startAngle and the endAngle are the start and end points of the arc respectively. The anticlockwise specifies the direction of the arc between the two start and end points.


3. Circle:

In HTML5, you can draw a circle using the arc () method. You have to set the start angle too. And the end angle is specified as 2 * PI.

Following is the syntax to draw a circle in HTML5: it is as follows:

Syntax:

arc (x, y, radius, startAngle, endAngle, anticlockwise)

Where,

  1. x, y - Specifies the coordinates of the center of a circle
  2. radius - Specifies the distance from the center to any point on the circle
  3. startAngle, endAngle - Specifies the start and end points in the circle
  4. anticlockwise - Draws the circle clockwise or anticlockwise and accepts a boolean value


How to create a circle using HTML5?

<html>
<head>
    <title>Canvas Arc</title>
    <script>
      window.onload = function () {
         var canvas = document.getElementById("mCanvas");
         var ctext = canvas.getContext("2d");
         var ctrX = canvas.width / 2;
         var ctrY = canvas.height / 2;
         var radius = 70;
         ctext.beginPath();
         ctext.arc(ctrX, ctrY, radius, 0, 2 * Math.PI, false);
         ctext.fillStyle = "DarkOrchid";
         ctext.fill();
         ctext.lineWidth = 4;
         ctext.strokeStyle = "black";
         ctext.stroke();
      }
    </script>
</head>
<body>
    <canvas id="mCanvas" width="356" height="150"></canvas>
</body>
</html>

In the code, a circle is defined by using the arc () method which has ctrX, ctrY, and radius as parameters. To define the arc with the points the startAngle is set to 0 and the endAngle is specified as 2*pI. The anticlockwise defines the direction of the path of an arc between the two start and end points.


4. Bezier curves:

Using HTML5 canvas, you can create a Bezier curve using the bezierCurveTo () method. Bezier curves are represented with two control points, context points, and an endpoint.

How to create a Bezier curve using HTML5?

<html>
<head>
    <title>Canvas Bezier Curve</title>
    <script>
      window.onload = function () {
         var canvas = document.getElementById("mCanvas");
         var ctext = canvas.getContext("2d");
         ctext.beginPath();
         ctext.moveTo(188, 130);
         ctext.bezierCurveTo(140, 10, 388, 10, 288, 100);
         ctext.lineWidth = 15;
         ctext.strokeStyle = "purple";
         ctext.stroke();
      }
    </script>
</head>
<body>
    <canvas id="mCanvas" width="378" height="200"></canvas>
</body>
</html>

In the code, the Bezier curve uses the bezierCurveTo () method. This method defines the current context point, two control points, and an endpoint. The context point uses the moveTo() method. The first portion of the curve is tangential to the imaginary line defined by the context point and the first control point. The second portion of the curve is tangential to the imaginary line which is defined by the second control point and the ending point.


5. Quadratic curves:

HTML5 canvas allows the user to create quadratic curves using the quadraticCurveTo () method. Quadratic curves are represented by a context point, an endpoint, and a control point.

How to create a quadratic curve using HTML5?

<html>
<head>
    <title>Canvas Quadratic Curve</title>
    <script>
      window.onload = function () {
         var canvas = document.getElementById("mCanvas");
         var ctext = canvas.getContext("2d");
         ctext.beginPath();
         ctext.moveTo(178, 150);
         ctext.quadraticCurveTo(220, 0, 320, 150);
         ctext.lineWidth = 15;
         ctext.strokeStyle = "Fuchsia";
         ctext.stroke();
      }
    </script>
</head>
<body>
    <canvas id="mCanvas" width="378" height="200"></canvas>
</body>
</html>

In the code, the control point defines the curve of the quadratic by two tangential lines that are connected to both the context point and the endpoint. The context point is represented using the moveTo() method. This method moves the control point from the context point to the endpoint to create a sharper curve. It also moves the control point close to the context point and end point to create broad curves.



Working with images

In HTML5, the user can draw image objects on a canvas using the drawImage() method. The drawImage() method can also draw parts of an image and increase or reduce the size of the image. This method accepts nine parameters, depending on the editing that is required on the image. The image object can be a video, an image, or another canvas element.

How to create an image using HTML5?

<html>
<head>
    <title>Canvas Image</title>
    <script>
      window.onload = function () {
         var canvas = document.getElementById("mCanvas");
         var ctext = canvas.getContext("2d");
         var imgObj = new Image();
         imgObj.onload = function () {
             ctext.drawImage(imgObj, 69, 50);
         };
         imgObj.src = "bird.jpg";
      }
    </script>
</head>
<body>
    <canvas id="mCanvas" width="368" height="300"></canvas>
</body>
</html>

In the code, the onload property is used. The source of the object is defined using the SRC property. The image has to be loaded first and then instantiated by the drawImage () method. This method takes the image object as a parameter with the x and y coordinates of the image.

You can also set the size of the image by adding two parameters width and height to the drawImage ()


How to resize images with height and width attributes using HTML5?

<html>
<head>
    <title>Canvas Image</title>
    <script>
      window.onload = function () {
        var canvas = document.getElementById("mCanvas");
        var ctext = canvas.getContext("2d");
        var x = 69;
        var y = 50;
        var w = 150;
        var h = 137;
        var imgObj = new Image();
        imgObj.onload = function () {
            ctext.drawImage(imgObj, x, y, w, h);
        };
        imgObj.src = "bird.jpg";
      };
    </script>
</head>
<body>
    <canvas id="mCanvas" width="278" height="200"></canvas>
</body>
</html>

In this code, The drawImage () method accepts two additional parameters: height and width for resizing the image.



Working with text

HTML5 canvas enables you to set the font, style, and size of text by using the font properties. The font style can be italic, normal, or bold. For setting the text color, you can use the fillStyle property of the canvas.

How to set the font, size, style, and color of the text on an HTML5 canvas.

<html>
<head>
    <title>Canvas Text</title>
    <script>
      window.onload = function () {
         var canvas = document.getElementById("mCanvas");
         var ctext = canvas.getContext("2d");
         ctext.font = "italic 30pt Calibri";
         ctext.fillStyle = "MediumVioletRed";
         ctext.fillText("Welcome to HTML5!", 40, 100);
      };
    </script>
</head>
<body>
    <canvas id="mCanvas" width="380" height="170"></canvas>
</body>
</html>

In the code, the font text is specified as Calibri, the style as italic, and the size is set to 30pt. The fillStyle property specifies the text color and the fillText property is used to set the text on the canvas.

In HTML5 canvas, the user can set the stroke color by using the strokeText() method and strokeStyle property of the canvas context.


The use of stroke text in HTML5 canvas.

<html>
<head>
    <title>Canvas Text</title>
    <script>
      window.onload = function () {
         var canvas = document.getElementById("mCanvas");
         var ctext = canvas.getContext("2d");
         var x = 80;
         var y = 110;
         ctext.font = "40pt Calibri";
         ctext.lineWidth = 2;
         ctext.strokeStyle = "Brown";
         ctext.strokeText("HTML5", x, y);
      };
    </script>
</head>
<body>
    <canvas id="mCanvas" width="360" height="200"></canvas>
</body>
</html>

In this code, the stroke color is set by using the strokeStyle property and the strokeText () method.



Using Transparency for Text in Canvas

There are two ways to set transparency for text and shapes. The first method is to use strokeStyle and fillStyle by using the RGB function. The second method is to use the globalAlpha drawing state property, which can be applied universally. The global alpha property is a value that ranges between 0 (fully transparent) and 1 (fully opaque).

The use of globalAlpha property.

<html>
<head>
    <title>Canvas Text and Rectangle</title>
    <script>
      window.onload = function () {
         var canvas = document.getElementById("mCanvas");
         var ctext = canvas.getContext("2d");
         ctext.fillStyle = "Indigo";
         ctext.strokeStyle = "black";
         ctext.lineWidth = 2;
         ctext.font = "italic 30pt Calibri";
         ctext.fillText("HTML5", 40, 100);
         ctext.strokeText("HTML5", 40, 100);
         ctext.fillStyle = "blue";
         ctext.globalAlpha = 0.5;
         ctext.fillRect(100, 10, 150, 100);
      };
    </script>
</head>
<body>
    <canvas id="mCanvas" width="350" height="170"></canvas>
</body>
</html>

In the code, fillStyle and strokeStyle are used to color the text. The 'HTML5' text lineWidth is specified as 2 and the font family is set to Calibri with italic style and font size to 30pt. The fillText property fills in the color and the strokeText property applies the stroke color to the HTML5 text. The fillStyle is set to blue and the globalAlpha property is set to 0.5. The fillRect (100, 10, 150, 100) specifies the x, y, height, and width of the rectangle.


HTML5 HTML Canvas Canvas in HTML5 Canvas element Drawing a line on Canvas Drawing objects in Canvas images in Canvas Text in Canvas Canvas in HTML HTML Canvas Examples canvas tag in HTML Canvas js

advertisement