The HTML canvas element is used to draw graphics using JavaScript. It gives you the ability to draw things like lines, arcs, rectangles, and images. A canvas, created using the canvas tag, only represents the container for where the graphics will be drawn. Let's take a look at how to define a canvas in HTML, and look at examples of how to draw on it.

Defining a Canvas

To create a canvas, we need to create a canvas element. We can do this by using the canvas tag.

HTML
<canvas></canvas>

Default HTML canvas.

Nothing appears because a canvas is an invisible element.

Width and Height

We can set the width and height of the canvas using the width and height attributes. Let's take a look at how to set the width and height of the canvas.

HTML
<canvas width="400" height="200"> </canvas>

Change background color

You can change the background color of a canvas using CSS:

  • HTML
  • CSS

Get the context of the canvas

To draw on a canvas, we need to get the context of the canvas. We can do this by using the getContext method.

JAVASCRIPT
const canvas = document.getElementById("canvas"); const context = canvas.getContext("2d");

Here are the value values when you use getContext:

  • 2d: This stands for CanvasRenderingContext2D
  • webgl: This stands for WebGLRenderingContext
  • webgl2: This stands for WebGL2RenderingContext
  • bitmaprenderer: This stands for ImageBitmapRenderingContext

Drawing a line

You can draw a line by using the lineTo method. Let's take a look at how to draw a line on a canvas. We'll create a line from the top left corner of the canvas to the bottom right corner.

  • HTML
  • JavaScript

Drawing a rectangle

You can draw a rectangle by using the rect method. Let's take a look at how to draw a rectangle on a canvas. We'll create a rectangle from the top left corner of the canvas to the bottom right corner.

  • HTML
  • JavaScript

Drawing a Circle

You can draw a circle by using the arc method. Let's take a look at how to draw a circle on a canvas.

  • HTML
  • JavaScript

Drawing Text

You can draw text by using the fillText method. Let's take a look at how to draw text on a canvas.

  • HTML
  • JavaScript

Drawing Stroke Text

You can draw stroke text by using the strokeText method. Let's take a look at how to draw stroke text on a canvas.

  • HTML
  • JavaScript

Drawing Linear Gradients

You can draw linear gradients by using the createLinearGradient method. Let's take a look at how to draw linear gradients on a canvas.

  • HTML
  • JavaScript

Drawing Radial Gradients

You can draw radial gradients by using the createRadialGradient method. Let's take a look at how to draw radial gradients on a canvas.

  • HTML
  • JavaScript

Resources

Next Lesson »
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.