Thursday, September 19, 2024

How to Animate Your Website Using the HTML5 Canvas

The HTML <canvas> element is used to draw graphics via scripting (usually JavaScript). But remember, it is only a container for graphics. You must use a script to actually draw the graphics. <Canvas> is a pixel container element, expressly mentioning that any object inside the area contains graphics. It has methods to draw circles, loops, charts, text, stunning graphics, illustrations, simple and complex animations, shapes and images that are accepted by all major browsers. It has a default size of 300px to 150px, but the size can be easily adjusted in the CSS code.

With the Canvas HTML5 API, you can write JavaScript code that can access the canvas area through a set of drawing functions, resulting in dynamic generated graphics.

Listing 1. A simple example

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:3px solid pink;">
Example with border
</canvas>
</body>
</html>

Drawing Lines

To draw a line, we should use paths. A path is a list of points, that are connected by segments of lines that can be of different shapes, different width or color. To create shapes using paths we use the beginPath(), that tells the browser to draw a new path lineTo (x, y) that establishes the beginning and end of the line by connecting the two points and the stroke() method.

Listing 2. Drawing Lines

<!DOCTYPE html>
<html>
<body>
<canvas id="mycanvas" width="300" height="150" style="border:3px solid aqua;">
</canvas>
<script>
var c = document.getElementById("mycanvas");
var context = c.getContext("2d");
context.beginPath();
context.moveTo(0,0);
context.lineTo(300,150);
context.stroke();
</script>
</body>
</html>

HTML5 Canvas Rounded Corners

To round the corners using HTML5 Canvas, we use the arcTo() method, defined by a terminal point, an end point and a radius.

Listing 3. Creating Rounded Corners

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 2px;
        padding: 5px;
      }
    </style>
  </head>
  <body>
    <canvas id="mycanvas" width="400" height="180"></canvas>
    <script>
      var canvas = document.getElementById('mycanvas');
      var context = canvas.getContext('2d');
      var rectWidth = 200;
      var rectHeight = 100;
      var rectX = 189;
      var rectY = 50;
      var cornerRadius = 50;
      context.beginPath();
      context.moveTo(rectX, rectY);
      context.lineTo(rectX + rectWidth - cornerRadius, rectY);
      context.arcTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + cornerRadius,                                    
                    cornerRadius);
      context.lineTo(rectX + rectWidth, rectY + rectHeight);
      context.lineWidth = 5;
      context.stroke();
    </script>
  </body>
</html>

HTML5 Canvas Draw a Circle

To draw a circle with HTML5 Canvas, we use the arc() method, defining the starting angle as terminal 0 and the finishing angle as 2 * Math PI.

Listing 4. Drawing a Circle

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 3px;
        padding: 5px;
      }
    </style>
  </head>
  <body>
    <canvas id="mycanvas" width="400" height="200"></canvas>
    <script>
      var canvas = document.getElementById('mycanvas');
      var context = canvas.getContext('2d');
      var centerX = canvas.width / 3;
      var centerY = canvas.height / 2;
      var radius = 90;
      context.beginPath();
      context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
      context.fillStyle = 'yellow';
      context.fill();
      context.lineWidth = 9;
      context.strokeStyle = 'aqua';
      context.stroke();
    </script>
  </body>
</html>

HTML5 Canvas Linear Gradient

To make a linear gradient using HTML5 Canvas, we help with the createdLinearGradient() method, defined by a line defining the gradient direction, and then, using the addColorStop() property, we can enter the desired colors, is along this imaginary line, somewhere between 0 and 1, where 0 is the starting point and 1 is the final point.

Listing 5. Adding a Liner Gradient

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 15px;
        padding: 5px;
      }
    </style>
  </head>
  <body>
    <canvas id="mycanvas" width="300" height="150"></canvas>
    <script>
      var canvas = document.getElementById('mycanvas');
      var context = canvas.getContext('2d');
      context.rect(0, 1, canvas.width, canvas.height);
      var grd = context.createLinearGradient(0, 1, canvas.width, canvas.height);
      grd.addColorStop(0, 'DarkViolet');   
      grd.addColorStop(1, 'IndianRed');
      context.fillStyle = grd;
      context.fill();
    </script>
  </body>
</html> 

HTML5 Canvas Radial Gradient

In order to create a radial gradient using HTML5 Canvas, we use the createdLinearGradient() method, defined with two imaginary circles, a starting and ending circle.

Listing 6. Adding a Radial Gradient

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 10px;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    <canvas id="mycanvas" width="600" height="200"></canvas>
    <script>
      var canvas = document.getElementById('mycanvas');
      var context = canvas.getContext('2d');
      context.rect(0, 0, canvas.width, canvas.height);
      var grd = context.createRadialGradient(250, 90, 18, 300, 70, 250);
      grd.addColorStop(0, 'LemonChiffon');
      grd.addColorStop(1, 'LawnGreen');
      context.fillStyle = grd;
      context.fill();
    </script>
  </body>
</html>

HTML5 Canvas Pattern

To create a canvas model using HTML5 Canvas, we can use the createPattern() method that repeats the specified element in the specified direction and then, using the fillStyle property, we can set the template object and fill the shape using fill().

Listing 7. Adding a Pattern

<!DOCTYPE html>
<html>
<body onload="init()">
    <canvas id="Canvas" width="200" height="150"></canvas>
    <img src="ball.gif" id="ball" hidden>
    <script>

	function init(){
      var canvas = document.getElementById('Canvas');
      
      var context = canvas.getContext('2d');
      
      var image=document.getElementById("ball");
      
      var pattern=context.createPattern(image,"repeat");
     
      context.rect(0,0,300,250);
      
      context.fillStyle=pattern;
      context.fill();
	  }
    </script>

</body>
</html>

HTML5 Canvas Draw Text

In order to draw a “filled” text using HTML5 Canvas, we should use the fillText() method. To set the font and size of the text, we need use the font property and to set the style the fillStyle property. The syntax is context.fillText(text,x,y,maxWidth); in which the parameters x and y represent the starting coordinates from which the text should be drawn, and the maxWidth parameter is optional and sets the maximum allowed width of the text.

Listing 8. Drawing Text

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 10px;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    <canvas id="mycanvas" width="500" height="250"></canvas>
    <script>
      var canvas = document.getElementById('mycanvas');
      var context = canvas.getContext('2d');
      context.font = 'italic 19pt Segoe UI Semibold';
	context.fillStyle = 'blue';
      context.fillText('HTML5 Canvas - draw a text', 20, 20);
    </script>
  </body>
</html>

HTML5 Canvas Text Stroke

The strokeText() method draws a text, only outlined, on the canvas. The syntax looks like this: context.strokeText(text,x,y,maxWidth); where the parameters x and y represents the starting coordinates from where the text should be drawn, and the maxWidth parameter is optional and sets the maximum allowed width of the text.

Listing 9. Adding Text Stroke

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 10px;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    <canvas id="mycanvas" width="600" height="200"></canvas>
    <script>
      var canvas = document.getElementById('mycanvas');
      var context = canvas.getContext('2d');
      context.font = '55pt Segoe UI Semibold';
      context.lineWidth = 3;
      // stroke color
      context.strokeStyle = 'purple';
      context.strokeText('Stroke Text', 60, 100);
    </script>
  </body>
</html>

HTML5 Canvas Draw Image

To draw an image using HTML5 Canvas, we help with the drawImage () method, defined by an image and a destination point (defines the top left corner of the image with respect to the top left corner of the canvas.

Tip: Use the onload property of the image object to load it before creating instant drawImage ()

Listing 10. Drawing an Image

<!DOCTYPE html>
<html>
<body>

<p>Image to use:
<img id="scream" width="200" height="200" src="ball.gif" alt="ball">

Canvas:
<canvas id="myCanvas" width="120" height="120" style="border:1px solid #d3d3d3;">

</canvas></p>

<script>
window.onload = function() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("scream");
    ctx.drawImage(img,10,10,160,160); 
}
</script>

</body>
</html>

Conclusion

This article explained how to use the HTML 5 Canvas for drawing an image, writing full and stroke text, showed how to create a pattern, draw a circle, rectangle and a line, and also how to create canvas gradients.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured