What exactly is HTML canvas?

What is canvas for HTML?

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. Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

Because you can now control the visuals, photos, and text dynamically with a scripting language, the CANVAS element allows you to add a lot more interaction to your web sites. The CANVAS element allows you to create animated components using photographs, photos, charts, and graphs.

The graphic to the left is created with <canvas>. It shows four elements: a red rectangle, a gradient rectangle, a multicolor rectangle, and a multicolor text.

On an HTML page, a canvas is a rectangular region. A canvas has no boundary and no content by default. This is how the markup appears.

 

getContext()

  • it have two parameter like
  • getContext(contextType, contextAttributes)
contextType:
  • A string containing the context identifier defining the drawing context associated to the canvas. Possible values are:

type of  contextType

  • contextType(2d)
  • contextType(webgl)
  • contextType(webgl2)
  • contextType(bitmaprenderer)
contextType(2d)
  • “2d”, leading to the creation of a CanvasRenderingContext2D object representing a two-dimensional rendering contex.
  • The drawing context is returned by the getContext() method, which is an object containing all of the drawing attributes and functions used to draw on the canvas. The getContext() method is used to gain access to the canvas tags 2D drawing functions.
contextType(webgl)
  • The drawing context is returned by the getContext() method, which is an object containing all of the drawing attributes and functions used to draw on the canvas. The getContext() method is used to gain access to the canvas tags 2D drawing functions.
contextType(webgl2)
  • “webgl2” will generate a WebGL2RenderingContext object representing a three-dimensional rendering context. This context is only available in browsers that support WebGL version 2. (OpenGL ES 3.0)
contextType(bitmaprenderer)
  • “bitmaprenderer” will generate an ImageBitmapRenderingContext that only allows you to replace the canvas’s content with a specific ImageBitmap.

contextAttributes

it’s Optional

const gl = canvas.getContext('webgl', {
antialias: false,
depth: false
});

moveTo(x,y);

  • moveTo having two parameter X and  Y axis,
  • The x-axis (horizontal) coordinate of the point.
  • The y-axis (vertical) coordinate of the point.
  • The moveTo() method moves the path to the specified point in the canvas, without creating a line.

lineTo(x, y)

  • The CanvasRenderingContext2D method lineTo(), part of the Canvas 2D API, adds a straight line to the current sub-path by connecting the sub-path’s last point to the specified (x, y) coordinates.
  • Like other methods that modify the current path, this method does not directly render anything. To draw the path onto a canvas, you can use the fill() or stroke() methods.
<canvas id="canvas" width="200" height="150" style="border:1px solid #000000;">
</canvas>
<script>

const canvas = document.getElementById('canvas'); 
const ctx = canvas.getContext('2d'); 
ctx.beginPath(); // Start a new path 
ctx.moveTo(30, 50); // Move the pen to (30, 50) 
ctx.lineTo(150, 100); // Draw a line to (150, 100) 
ctx.stroke(); // Render the path

</script>

output :

img1-6

stroke(path)

  • With the current stroke style, the Canvas 2D API strokes (outlines) the current or provided route.
  • Strokes are drawn parallel to the path’s centre; that is, half of the stroke is drawn on the inner side and half on the outer side.

Examples

A simple stroked rectangle, This example creates a rectangle using the rect() method, and then draws it to the canvas using stroke().

<canvas id="canvas"></canvas>

<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.rect(10, 10, 150, 100);
ctx.stroke();
</script>

output :

example creates a rectangle

Draw a Circle

const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
// Now let us define the position and radius:-

const X = canvas.width / 2;
const Y = canvas.height / 2;
const radius = 45;
// Now let us set the color and line width:-

ctx.lineWidth = 3;
ctx.strokeStyle = '#FF0000';
//Now, to draw the circle, we have to use the arc method and set the angle to 2 X π

ctx.beginPath();
ctx.arc(X, Y, radius, 0, 2 * Math.PI, false);
ctx.stroke();

output :

Draw a Text

In HTML5, canvas element supports basic text rendering on a line-by-line basis. There are two methods fillText() and strokeText() to draw text on canvas. You can use font property (type : string) to specify a number of text setting such as style, weight, size, and font. The style can be normal, italic, or bold. Default style is normal.
Code example of font property :

font = 'italic 400 12px, sans-serif';

The “400” font-weight doesn’t appear because that is the default value.

<canvas id="DemoCanvas" width="500" height="600"></canvas> 
<script>
var canvas = document.getElementById("DemoCanvas");
if (canvas.getContext) 
{
 var ctx = canvas.getContext('2d');
 ctx.font = 'italic 32px sans-serif';
 ctx.fillText('HTML5 Canvas Tutorial', 10, 50); 
}
</script>

output :-

advance example 1:

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>canvas</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <canvas></canvas>
    <script src="canvas.js"></script>
</body>

</html>

style.css

html,
body {
    margin: 0px;
    padding: 0px;
    box-sizing: border-box;
    overflow: hidden;
    background: #010101;
    font-weight: 700;
    text-transform: uppercase;
    font-family: "Source Sans Pro", sans-serif;
}

canvas.js

<script>
      var canvas = document.querySelector('canvas');
      var c = canvas.getContext('2d');
      var mouse = {
          x: undefined,
          y: undefined
      }
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;

      //Function to get a random color
      function getRandomColor() {

          var colorArray = [
              '#FFA500',
              '#FF8C00',
              '#F3B562',
              '#FF6347'
          ];
          return colorArray[Math.floor(Math.random() * colorArray.length)];
      }
      //Circle object	
      function circle() {
          var ctx = canvas.getContext("2d");
          ctx.beginPath();
          ctx.arc(100, 75, 50, 0, 2 * Math.PI);
          ctx.stroke();
      }
      function Circle(x, y, dx, dy, radius, color) {
          var maxRadius = 20;
          var minRadius = radius;
          var proximity = 30;

          this.x = x || 50;
          this.y = y || 50;
          this.dx = dx || 5;
          this.dy = dy || 5;
          this.radius = radius || 15;
          this.color = color || 'blue';
          //Draw circle
          this.draw = function() {
              c.beginPath();
              c.arc(this.x, this.y, this.radius, Math.PI * 2, false);
              c.fillStyle = this.color;
              c.fill();
          }
          //Update circle position
          this.update = function() {
              this.dy = ((this.y > (innerHeight - this.radius)) || (this.y < this.radius)) ? -this.dy : this.dy;
              this.y += this.dy;
              this.draw();
          }
      }
      var circleQuantity = 200;
      var circleMinSize = 4;
      var circleMaxSize = 20;
      var circleArray = [];

      function init() {

          circleArray = [];

          for (var i = 0; i < circleQuantity; i++) {

              var radius = (circleMinSize - 1) + parseInt((circleMaxSize - circleMinSize) * Math.random());
              var x = Math.random() * (innerWidth - radius * 2) + radius;
              var y = Math.random() * (innerHeight - radius * 2) + radius;
              var dx = (Math.random() - 0.5) * 5;
              var dy = (Math.random() - 0.5) * 5;
              var color = getRandomColor();

              circleArray[i] = new Circle(x, y, dx, dy, radius, color);
              circleArray[i].draw();
          }
      }
      init();
      //Trigger the animation
      function animate() {
          //Clear full canvas
          //c.clearRect(x, y, width, height);
          c.clearRect(0, 0, innerWidth, innerHeight);

          //Animate circles
          for (var i = 0; i < circleArray.length; i++) {
              circleArray[i].update();
          }
          //Loop animation
          requestAnimationFrame(animate);
      }
      animate();
  </script>

ouput :-

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories