Skip to content
","url":"https://ez4code.com/snippets/html-canvas","keywords":"canvas, graphics","author":{"@type":"Person","name":"EZ4Code Team"},"publisher":{"@type":"Organization","name":"EZ4Code","logo":{"@type":"ImageObject","url":"https://ez4code.com/logo.png"}},"datePublished":"2024-01-01","dateModified":"2026-08-01","image":"https://ez4code.com/og-image.png"}
HTML

Canvas

Canvas drawing.

By EZ4Code Team
canvasgraphics

Code

<canvas id="myCanvas" width="500" height="400"></canvas>

<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// Rectangle
ctx.fillStyle = '#3498db';
ctx.fillRect(10, 10, 100, 50);
ctx.strokeStyle = '#2c3e50';
ctx.strokeRect(10, 10, 100, 50);

// Circle
ctx.beginPath();
ctx.arc(200, 50, 30, 0, Math.PI * 2);
ctx.fillStyle = '#2ecc71';
ctx.fill();

// Line
ctx.beginPath();
ctx.moveTo(10, 100);
ctx.lineTo(200, 150);
ctx.strokeStyle = '#e74c3c';
ctx.lineWidth = 3;
ctx.stroke();

// Text
ctx.font = '20px Arial';
ctx.fillStyle = '#333';
ctx.fillText('Hello Canvas', 10, 200);

// Gradient
const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, '#3498db');
gradient.addColorStop(1, '#2ecc71');
ctx.fillStyle = gradient;
ctx.fillRect(10, 250, 200, 50);

// Animation
let x = 0;
function animate() {
    ctx.clearRect(0, 350, canvas.width, 50);
    ctx.fillStyle = '#9b59b6';
    ctx.fillRect(x, 370, 30, 20);
    x = (x + 2) % canvas.width;
    requestAnimationFrame(animate);
}
animate();

// Image
const img = new Image();
img.onload = () => ctx.drawImage(img, 300, 10, 100, 80);
img.src = 'image.png';
</script>

Explanation

The Canvas 2D API provides drawing for rectangles, circles, paths, text, gradients; requestAnimationFrame implements animation.

More HTML Snippets