Canvas API Reference
HTML5 Canvas drawing, animations, and image manipulation
Setup & Context
const canvas = document.getElementById("myCanvas"); # get canvas
const ctx = canvas.getContext("2d"); # 2D context
canvas.width = 800; # set width
canvas.height = 600; # set height
ctx.clearRect(0, 0, canvas.width, canvas.height); # clear canvas
Drawing Shapes
ctx.fillRect(x, y, width, height); # filled rectangle
ctx.strokeRect(x, y, width, height); # outlined rectangle
ctx.clearRect(x, y, width, height); # clear area
ctx.beginPath(); # start new path
ctx.arc(x, y, radius, 0, Math.PI * 2); # circle
ctx.fill(); # fill shape
ctx.stroke(); # draw outline
Paths & Lines
ctx.moveTo(x, y); # move pen position
ctx.lineTo(x, y); # draw line
ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y); # curve
ctx.closePath(); # close path
ctx.lineWidth = 5; # line thickness
ctx.lineCap = "round"; # line end style
Styles & Colors
ctx.fillStyle = "#ff0000"; # fill color
ctx.strokeStyle = "rgb(0,0,255)"; # stroke color
ctx.globalAlpha = 0.5; # transparency
ctx.shadowColor = "#000"; # shadow color
ctx.shadowBlur = 10; # shadow blur
ctx.shadowOffsetX = 5; # shadow position
Images & Animation
const img = new Image(); # create image
img.src = "image.png"; # set source
ctx.drawImage(img, x, y); # draw image
ctx.drawImage(img, x, y, width, height); # scaled
function animate() {
requestAnimationFrame(animate); # smooth animation
ctx.clearRect(0, 0, canvas.width, canvas.height);
}