Introduction
Canvas is one of the most powerful parts of HTML5. It can render animations, games, particle systems, charts, physics simulations, image processing, and custom drawing operations.
1. Drawing Images
const img = new Image();
img.src = "car.png";
img.onload = () => {
ctx.drawImage(img, 50, 50, 200, 120);
};
2. Pixel Manipulation (ImageData)
const data = ctx.getImageData(0, 0, canvas.width, canvas.height);
for (let i = 0; i < data.data.length; i += 4) {
data.data[i] = 255 - data.data[i]; // invert R
data.data[i+1] = 255 - data.data[i+1]; // invert G
data.data[i+2] = 255 - data.data[i+2]; // invert B
}
ctx.putImageData(data, 0, 0);
3. Advanced Gradients
let g = ctx.createLinearGradient(0,0,600,0);
g.addColorStop(0, "red");
g.addColorStop(0.5, "yellow");
g.addColorStop(1, "green");
ctx.fillStyle = g;
ctx.fillRect(0,0,600,90);
4. Bezier Curves
ctx.beginPath();
ctx.moveTo(50,150);
ctx.bezierCurveTo(200,0, 300,300, 500,150);
ctx.strokeStyle = "white";
ctx.stroke();
5. Text Effects
ctx.font = "50px Arial";
ctx.fillStyle = "cyan";
ctx.shadowColor = "blue";
ctx.shadowBlur = 20;
ctx.fillText("CodeTweakrs", 120,120);
6. Transformations (rotate, scale, translate)
ctx.translate(300,150);
ctx.rotate(Math.PI / 4);
ctx.fillStyle = "orange";
ctx.fillRect(-50,-50,100,100);
7. Animation Loop (core pattern)
function loop(){
ctx.clearRect(0,0,width,height);
// draw objects...
requestAnimationFrame(loop);
}
loop();
8. Collision Detection (simple)
function hit(a,b){
return (
a.x < b.x + b.w &&
a.x + a.w > b.x &&
a.y < b.y + b.h &&
a.y + a.h > b.y
);
}
9. Physics Simulation Basics
ball.vy += 0.5; // gravity
ball.y += ball.vy;
if(ball.y > ground){
ball.y = ground;
ball.vy *= -0.6; // bounce
}
10. Particle System
class Particle {
constructor(x,y){
this.x=x; this.y=y;
this.vx=(Math.random()-0.5)*4;
this.vy=(Math.random()-0.5)*4;
}
update(){
this.x += this.vx;
this.y += this.vy;
}
}
11. Saving Canvas as Image
const url = canvas.toDataURL("image/png");
12. Summary
- Canvas can animate, draw images, process pixels
- Supports curves, transforms, gradients, shadows
- Used in games, charts, simulators, dashboards
- requestAnimationFrame is the animation loop backbone
- Pixel-level editing enables photo filters and effects
- Export drawings as PNG/JPEG easily