html
/

HTML Canvas: Drawing Graphics with JavaScript

Last Sync: Today

On this page

11
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

html

HTML Canvas: Drawing Graphics with JavaScript

What is HTML Canvas?

The <canvas> element is used to draw graphics on a webpage using JavaScript. It can be used for animations, games, charts, and visual effects.

Basic Syntax

HTMLRead-only
1
<canvas id="myCanvas" width="300" height="200"></canvas>

Accessing Canvas in JavaScript

JavaScriptRead-only
1
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

Drawing a Rectangle

JavaScriptRead-only
1
ctx.fillStyle = 'blue';
ctx.fillRect(20, 20, 150, 100);

Drawing a Line

JavaScriptRead-only
1
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();

Drawing a Circle

JavaScriptRead-only
1
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke();

Adding Text

JavaScriptRead-only
1
ctx.font = '20px Arial';
ctx.fillText('Hello Canvas', 50, 50);

Canvas vs SVG

FeatureCanvasSVG
RenderingPixel-basedVector-based
PerformanceBetter for complex graphicsBetter for simple shapes
InteractivityRequires JSBuilt-in with DOM
Use CaseGames, animationsIcons, diagrams

Best Practices

  • Always define width and height
  • Use JavaScript for drawing logic
  • Optimize for performance in animations
  • Clear canvas before redrawing
  • Use requestAnimationFrame for smooth animations

Common Mistakes

  • Forgetting to get context (getContext)
  • Not setting canvas size properly
  • Redrawing without clearing canvas
  • Using canvas for static content unnecessarily

Conclusion

HTML canvas is a powerful tool for creating dynamic graphics and animations. It is widely used in games, visualizations, and interactive applications.

Try it yourself

<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
const c = document.getElementById('myCanvas');
const ctx = c.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(20, 20, 100, 50);
</script>

Test Your Knowledge

Q1
of 3

Which tag is used for drawing graphics?

A
<draw>
B
<canvas>
C
<svg>
D
<graphics>
Q2
of 3

Which language is required for canvas?

A
CSS
B
HTML
C
JavaScript
D
Python
Q3
of 3

Which method gets drawing context?

A
getCanvas()
B
getContext()
C
draw()
D
createContext()

Frequently Asked Questions

What is canvas used for?

It is used to draw graphics and animations using JavaScript.

Does canvas work without JavaScript?

No, JavaScript is required to draw on canvas.

What is the difference between canvas and SVG?

Canvas is pixel-based, while SVG is vector-based.

Previous

html accessibility

Next

html svg

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.