HTML5 Canvas Drawing Techniques and API Usage
Cenvas Element Basics
The HTML5 canvas element creates a drawing surface for JavaScript rendering:
<canvas id="drawingSurface" width="400" height="400">
Canvas not supported in your browser
</canvas>
Canvas itself has no drawing capabilities - all rendering occurs through JavaScript API calls.
Browser Compatibility Check
const canvas = document.getElementById('drawingSurface');
if (!canvas.getContext) {
console.warn('Canvas not supported');
} else {
console.log('Canvas supported');
}
Drawing Fundametnals
Line Drawing
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(200, 200);
ctx.strokeStyle = 'blue';
ctx.stroke();
Rectangle Drawing
ctx.fillStyle = 'rgb(255, 0, 0)';
ctx.fillRect(30, 30, 150, 100);
Circle Drawing
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = 'green';
ctx.fill();
ctx.closePath();
Text Rendering
ctx.font = '24px Arial';
ctx.fillStyle = 'purple';
ctx.fillText('Hello Canvas', 50, 50);
ctx.strokeStyle = 'orange';
ctx.lineWidth = 1;
ctx.strokeText('Outlined Text', 50, 100);
Image Handling
const img = new Image();
img.src = 'example.png';
img.onload = function() {
ctx.drawImage(img, 0, 0, 200, 200);
};
Shape Construction
// Triangle
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(200, 200);
ctx.lineTo(50, 200);
ctx.closePath();
ctx.stroke();
Transformations
ctx.save();
ctx.translate(100, 100);
ctx.rotate(Math.PI / 4);
ctx.fillRect(0, 0, 50, 50);
ctx.restore();
Practical Exercises
- Draw a diagonal line
- Create a filled circle
- Render a rectangle with border
- Display formatted text
- Load and position an image
- Apply image transformations