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.
Add Border to Canvas
Canvas is invisible by default.
Use CSS border to make it visible.
Get Canvas Context
The getContext() method returns a drawing object.
Draw a Line
Use:
moveTo()lineTo()stroke()
to draw lines.
Draw Rectangle
Use fillRect() to create filled rectangles.
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.
Clear Rectangle Area
Use clearRect() to erase an area.
Canvas Colors
Use fillStyle to change fill color.
Draw Circle
Use the arc() method to create circles.
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.
Draw Image
Use drawImage() to display images.
Canvas Gradient
Use createLinearGradient() to create gradients.
Canvas Shadow
Use shadow properties to add shadow effects.
Canvas Animation
Use requestAnimationFrame() for smooth animations.
Canvas vs SVG
Canvas |
SVG |
|---|---|
Pixel based |
Vector based |
Good for games |
Good for icons |
Faster rendering |
Better scaling |
Uses JavaScript |
Uses XML |