HTML Canvas

You’ve got your webpage looking sharp with Text, Forms, and maybe some interactive clicks. But what if you could draw stuff, like a square, a smiley, or even a mini game, right there in the browser? That’s where the HTML <canvas> tag comes in. It’s like a blank art board you can paint on with JavaScript, and it’s one of those HTML5 tricks that feels like pure magic. I remember the first time I made a red box appear. It wasn’t Picasso, but it was mine, and that was enough to hook me. Let’s mess around with it and see what we can do!

First, you drop the <canvas> tag in your HTML:

<canvas id="myCanvas" width="300" height="200"></canvas>

That’s your blank slate, 300 pixels wide, 200 tall. It won’t show anything yet, it’s invisible until you grab it with JavaScript.

Here’s a basic script to draw a rectangle:

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

Load that, and a red rectangle pops up, 50 pixels from the top and left, 100 wide, 80 tall. I tried this and grinned like a kid with crayons. That ctx thing? It’s your paintbrush, and fillRect is one stroke.

You can get wilder. Draw a line:

<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(100, 100);
ctx.stroke();
</script>

That’s a diagonal slash. I botched my first try by forgetting stroke(), and nothing showed up. Live and learn! Canvas can do circles, text, even animations if you dig deeper, but start small.

Here’s one I played with:

<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 50, 50);
</script>

A little blue square, just chilling. It’s not fancy, but it’s yours. Next time you’re coding, toss in a <canvas> and sketch something. It’s like turning your page into a sketchbook!

How-To Guides for HTML

No How-To Guide is available right now.

Keep Learning & Level Up!

Enhance your HTML skills with our in-depth tutorials and interactive quizzes.

Explore HTML Quiz