const ctx = document.getElementById('shapeCanvas').getContext('2d');
ctx.fillStyle = 'orange';
ctx.fillRect(20,20,100,50);
ctx.strokeStyle = 'red';
ctx.strokeRect(150,20,100,50);
ctx.beginPath();
ctx.moveTo(50,150);
ctx.lineTo(150,150);
ctx.lineTo(100,100);
ctx.closePath();
ctx.fillStyle = 'lime';
ctx.fill();
ctx.stroke();
Draws rectangles and a triangle using fillRect, strokeRect, and paths.
const ctx = document.getElementById('textCanvas').getContext('2d');
ctx.font = '24px Fira Code';
ctx.fillStyle = 'lime';
ctx.fillText('Hello Canvas!', 50,100);
ctx.strokeStyle = 'orange';
ctx.strokeText('Outline Text',50,150);
Draws filled and outlined text on canvas.
const ctx = document.getElementById('imageCanvas').getContext('2d');
const img = new Image();
img.src = 'https://via.placeholder.com/150';
img.onload = () => {
ctx.drawImage(img,50,25,150,150);
};
Loads and draws an image onto the canvas.
const ctx = document.getElementById('transCanvas').getContext('2d');
ctx.fillStyle = 'skyblue';
ctx.translate(200,100);
ctx.rotate(Math.PI/6);
ctx.fillRect(-50,-25,100,50);
Moves origin, rotates, then draws rectangle.
const ctx = document.getElementById('gradCanvas').getContext('2d');
const grad = ctx.createLinearGradient(0,0,400,0);
grad.addColorStop(0,'red');
grad.addColorStop(1,'blue');
ctx.fillStyle = grad;
ctx.fillRect(0,0,400,200);
Linear gradient from red to blue fills the rectangle.
let x=0;
function animate(){
ctx.clearRect(0,0,400,200);
ctx.fillStyle='orange';
ctx.fillRect(x,80,50,50);
x+=2;
if(x>400)x=-50;
requestAnimationFrame(animate);
}
animate();
Animating rectangle moving horizontally.
const ctx = document.getElementById('pixelCanvas').getContext('2d');
const imgData = ctx.createImageData(200,200);
for(let i=0;i<imgData.data.length;i+=4){
imgData.data[i]=Math.random()*255;
imgData.data[i+1]=Math.random()*255;
imgData.data[i+2]=Math.random()*255;
imgData.data[i+3]=255;
}
ctx.putImageData(imgData,0,0);
Random colors assigned to each pixel and rendered.