HTML Canvas
Master real-time graphic rendering through JavaScript-powered Canvas API operations
Canvas elements establish JavaScript-controlled rendering contexts for dynamic graphic generation. These container elements require scripting for visual outputβthe tag itself provides only the drawing surface framework.
What is HTML Canvas?
The <canvas>
element provides a bitmap canvas on which you can draw using JavaScript. It's like a blank drawing surface where you can create:
- Shapes (rectangles, circles, lines, paths)
- Text with various fonts and styles
- Images and image manipulation
- Gradients and patterns
- Animations and games
- Charts and data visualizations
Key Point
Canvas delivers comprehensive programmatic graphic manipulation capabilities. JavaScript handles all rendering operations while canvas elements function purely as drawable surface containers.
The Canvas Element
To use canvas, you must define it in your HTML with width and height attributes:
Basic Canvas Element
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
Your browser does not support the HTML canvas tag.
</canvas>
Result:
Important attributes:
id
- Used to reference the canvas in JavaScriptwidth
- Sets the canvas width in pixels (default: 300)height
- Sets the canvas height in pixels (default: 150)- The fallback text is displayed in browsers that don't support canvas
β οΈ Important
Always specify the width and height using HTML attributes, not CSS. CSS sizing can cause distortion because it scales the canvas after rendering.
Drawing a Rectangle
To draw on the canvas, you must first get the canvas context and then use drawing methods:
Example - Red Rectangle
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000;">
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 150, 75);
</script>
Result:
Explanation:
getElementById("myCanvas")
- Find the canvas elementgetContext("2d")
- Get the 2D drawing contextfillStyle = "#FF0000"
- Set the fill color to redfillRect(0, 0, 150, 75)
- Draw a filled rectangle at (x:0, y:0) with width 150 and height 75
Canvas Coordinates
The HTML canvas is a two-dimensional grid. The upper-left corner of the canvas has coordinates (0,0).
β
β
β
βΌ
Y-axis
Key points:
- X increases to the right
- Y increases downward
- All coordinates are in pixels
- Drawing outside the canvas bounds is clipped
Drawing Shapes
Rectangle Methods
Canvas provides three methods for drawing rectangles:
Example - Multiple Rectangles
<canvas id="rectCanvas" width="300" height="150" style="border:1px solid #000;">
</canvas>
<script>
var canvas = document.getElementById("rectCanvas");
var ctx = canvas.getContext("2d");
// Filled rectangle
ctx.fillStyle = "#FF6347";
ctx.fillRect(20, 20, 100, 80);
// Stroked rectangle
ctx.strokeStyle = "#4CAF50";
ctx.lineWidth = 5;
ctx.strokeRect(150, 20, 100, 80);
// Clear rectangle (makes a hole)
ctx.clearRect(50, 40, 40, 40);
</script>
Result:
Drawing Paths
Paths are used to draw lines, circles, arcs, and complex shapes. A path is a list of points connected by lines.
Path Methods
Example - Drawing a Line
<canvas id="lineCanvas" width="200" height="100" style="border:1px solid #000;">
</canvas>
<script>
var canvas = document.getElementById("lineCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(180, 80);
ctx.strokeStyle = "#2196F3";
ctx.lineWidth = 5;
ctx.stroke();
</script>
Result:
Drawing a Circle
<canvas id="circleCanvas" width="200" height="150" style="border:1px solid #000;">
</canvas>
<script>
var canvas = document.getElementById("circleCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = "#9C27B0";
ctx.fill();
ctx.strokeStyle = "#000";
ctx.lineWidth = 3;
ctx.stroke();
</script>
Result:
arc() parameters:
x, y
- Center coordinatesr
- RadiusstartAngle
- Start angle in radiansendAngle
- End angle in radians2 * Math.PI
- Complete circle (360 degrees)
Drawing Text
Canvas provides methods for drawing text on the canvas:
Example - Canvas Text
<canvas id="textCanvas" width="300" height="100" style="border:1px solid #000;">
</canvas>
<script>
var canvas = document.getElementById("textCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillStyle = "#FF5722";
ctx.fillText("Hello Canvas!", 10, 50);
ctx.font = "20px Verdana";
ctx.strokeStyle = "#3F51B5";
ctx.strokeText("Outlined Text", 10, 80);
</script>
Result:
Gradients
Canvas supports linear and radial gradients that can be used to fill or stroke shapes.
Linear Gradient
<canvas id="gradientCanvas" width="200" height="100" style="border:1px solid #000;">
</canvas>
<script>
var canvas = document.getElementById("gradientCanvas");
var ctx = canvas.getContext("2d");
// Create gradient
var gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, "#FF0000");
gradient.addColorStop(0.5, "#FFFF00");
gradient.addColorStop(1, "#00FF00");
// Fill with gradient
ctx.fillStyle = gradient;
ctx.fillRect(10, 10, 180, 80);
</script>
Result:
createLinearGradient(x0, y0, x1, y1):
x0, y0
- Start point coordinatesx1, y1
- End point coordinatesaddColorStop(position, color)
- Adds a color at a position (0 to 1)
Radial Gradient
<canvas id="radialCanvas" width="200" height="200" style="border:1px solid #000;">
</canvas>
<script>
var canvas = document.getElementById("radialCanvas");
var ctx = canvas.getContext("2d");
// Create radial gradient
var gradient = ctx.createRadialGradient(100, 100, 10, 100, 100, 90);
gradient.addColorStop(0, "#FFFFFF");
gradient.addColorStop(1, "#FF1744");
// Fill with gradient
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 200, 200);
</script>
Result:
Drawing Images
You can draw images on the canvas using the drawImage()
method:
Example - Drawing an Image
<canvas id="imgCanvas" width="300" height="200" style="border:1px solid #000;">
</canvas>
<script>
var canvas = document.getElementById("imgCanvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 10, 10, 280, 180);
};
img.src = "image.jpg";
</script>
drawImage() variations:
drawImage(img, x, y)
- Draw at positiondrawImage(img, x, y, width, height)
- Draw and scaledrawImage(img, sx, sy, sw, sh, dx, dy, dw, dh)
- Crop and draw
Canvas Properties and Methods Summary
Style Properties
Common Methods
fillRect()
,strokeRect()
,clearRect()
- Rectangle methodsbeginPath()
,closePath()
- Path methodsmoveTo()
,lineTo()
- Drawing linesarc()
,arcTo()
- Drawing arcsquadraticCurveTo()
,bezierCurveTo()
- Drawing curvesfillText()
,strokeText()
- Drawing textdrawImage()
- Drawing imagessave()
,restore()
- Saving and restoring state