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
Accessible Form with Inputs
Build an accessible HTML form with labels, inputs, select, and checkbox.
Table with Thead Tbody Tfoot
Structure tabular data with thead, tbody, tfoot, and caption in HTML.
Responsive Images and Video
Embed responsive images with srcset, video, audio, and figure in HTML.
Links Anchors and Download
Create internal, external, anchor, email, phone, and download links in HTML.
Semantic Tags
HTML5 semantic structure.
Form Validation
HTML5 form validation.