Advertisement

Google Ad Slot: content-top

HTML Canvas Graphics


HTML Canvas

The HTML <canvas> element is used to draw graphics on a web page using JavaScript.

Canvas can be used for:

  • Drawing shapes
  • Creating animations
  • Building games
  • Drawing charts
  • Image editing

Canvas itself is just an empty container.

JavaScript is required to draw inside the canvas.


Create a Canvas

Use the <canvas> tag to create a drawing area.

Syntax

<canvas></canvas>

Canvas Width and Height

Always define the width and height of the canvas.

Example

Add Border to Canvas

Canvas is invisible by default.

Use CSS border to make it visible.

Example
Try it yourself

Get Canvas Context

The getContext() method returns a drawing object.

Example

Draw a Line

Use:

  • moveTo()
  • lineTo()
  • stroke()

to draw lines.

Example
Try it yourself

Draw Rectangle

Use fillRect() to create filled rectangles.

Example
Try it yourself

Rectangle Parameters

The fillRect() method contains 4 values.

Parameter

Description

x

Horizontal position

y

Vertical position

width

Rectangle width

height

Rectangle height


Draw Rectangle Border

Use strokeRect() to create rectangle borders.

Example
Try it yourself

Clear Rectangle Area

Use clearRect() to erase an area.

Example
Try it yourself

Canvas Colors

Use fillStyle to change fill color.

Example
Try it yourself

Draw Circle

Use the arc() method to create circles.

Example
Try it yourself

Circle Parameters

Parameter

Description

x

Center x position

y

Center y position

radius

Circle size

startAngle

Starting angle

endAngle

Ending angle


Draw Text

Use fillText() to add text.

Example
Try it yourself

Draw Image

Use drawImage() to display images.

Example
Try it yourself

Canvas Gradient

Use createLinearGradient() to create gradients.

Example
Try it yourself

Canvas Shadow

Use shadow properties to add shadow effects.

Example
Try it yourself

Canvas Animation

Use requestAnimationFrame() for smooth animations.

Example
Try it yourself

Canvas vs SVG

Canvas

SVG

Pixel based

Vector based

Good for games

Good for icons

Faster rendering

Better scaling

Uses JavaScript

Uses XML