HTML Canvas cheat sheet
Comficker
Posted on October 6, 2023
Certainly! Here's an HTML Canvas cheat sheet that covers some of the commonly used methods and properties:
Canvas Setup:
<!-- Create a canvas element -->
<canvas id="myCanvas"></canvas>
<!-- Get the canvas element in JavaScript -->
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
Drawing Shapes:
// Draw a rectangle
ctx.beginPath();
ctx.rect(x, y, width, height);
ctx.fillStyle = "color";
ctx.fill();
ctx.closePath();
// Draw a circle
ctx.beginPath();
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
ctx.fillStyle = "color";
ctx.fill();
ctx.closePath();
// Draw a line
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle = "color";
ctx.stroke();
ctx.closePath();
Text Manipulation:
ctx.font = "fontStyle fontSize fontFamily";
ctx.fillStyle = "color";
ctx.fillText("Text", x, y);
ctx.strokeText("Text", x, y);
Colors and Styles:
// Set fill color
ctx.fillStyle = "color";
// Set stroke color
ctx.strokeStyle = "color";
// Set line width
ctx.lineWidth = width;
// Set line join style
ctx.lineJoin = "style";
// Set line cap style
ctx.lineCap = "style";
// Set shadow
ctx.shadowColor = "color";
ctx.shadowBlur = value;
ctx.shadowOffsetX = value;
ctx.shadowOffsetY = value;
Transformations:
// Translate the canvas origin
ctx.translate(x, y);
// Scale the canvas
ctx.scale(scaleX, scaleY);
// Rotate the canvas
ctx.rotate(angle);
// Reset transformations
ctx.setTransform(1, 0, 0, 1, 0, 0);
Image Manipulation:
// Draw an image
var img = new Image();
img.src = "imageURL";
img.onload = function() {
ctx.drawImage(img, x, y, width, height);
}
// Draw a portion of an image
ctx.drawImage(img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
// Create a pattern with an image
var pattern = ctx.createPattern(image, "repeat/repeat-x/repeat-y/no-repeat");
ctx.fillStyle = pattern;
ctx.fill();
Demo using html canvas: Pixel Art Editor
💖 💪 🙅 🚩
Comficker
Posted on October 6, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.