Skip to main content

Learn HTML Canvas: Create Graphics and Interactive Visualizations

HTML Canvas is a powerful tool for creating graphics, animations, and interactive visualizations in web applications. It is an HTML element that allows you to draw graphics using JavaScript.

As an example:

Editor

Loading...

In this example:

  • The id attribute is used to uniquely identify the canvas element. The width and height attributes specify the dimensions of the canvas in pixels.
  • We first retrieve the canvas element using its id attribute.
  • We then get the canvas context using the getContext() method, which returns a drawing context on the canvas.
  • We use the beginPath() method to begin the drawing path and the arc() method to draw a circle at the center of the canvas with a radius of 100 pixels.
  • Finally, we call the stroke() method to draw the circle stroke on the canvas.

Draw Circular Gradient

To draw a circular gradient on an HTML canvas, you can use the createRadialGradient() method of the canvas context object. This method creates a radial gradient object that you can use to fill shapes on the canvas.

As an example:

Editor

Loading...

In this example:

  • We first retrieve the canvas element using its id attribute.
  • We then get the canvas context using the getContext() method.
  • We create a radial gradient object using the createRadialGradient() method, which takes six arguments: the x and y coordinates of the inner circle center, the radius of the inner circle, the x and y coordinates of the outer circle center, and the radius of the outer circle.
  • We then define the gradient colors and stops using the addColorStop() method.
  • We set the fill style of the canvas context to the gradient using the fillStyle property, and then fill a circle on the canvas using the fill() method.

Draw Linear Gradient

To draw a linear gradient on an HTML canvas, you can use the createLinearGradient() method of the canvas context object. This method creates a linear gradient object that you can use to fill shapes on the canvas.

As an example:

Editor

Loading...

In this example:

  • We first retrieve the canvas element using its id attribute.
  • We then get the canvas context using the getContext() method.
  • We create a linear gradient object using the createLinearGradient() method, which takes four arguments: the x and y coordinates of the starting point of the gradient, and the x and y coordinates of the ending point of the gradient.
  • We then define the gradient colors and stops using the addColorStop() method.
  • We set the fill style of the canvas context to the gradient using the fillStyle property, and then fill a rectangle on the canvas using the fillRect() method.