Chapter 2
Intro to CanvasRenderingContext2D
Learn to paint on a <canvas>
Picking up from Chapter 1, you now have a canvas on the page and a 2D context to draw into. If you're looking at the size of the scrollbar on this page and wondering what you've gotten yourself into—don't worry. This chapter is a reference as much as a tutorial, so feel free to skip around!
With that said, there are a few essentials you should know first.
Canvas intro, basic concepts, and setup
Canvas setup
Chapter 1 left off with starter code and a simple fillRect draw call. For now we can remove that blue rectangle. The remaining code is the starting point we'll assume is in place for all of the other demos in this chapter.
What does each line do?
The first line creates a canvas element, exactly like writing <canvas> in index.html would have done.
This canvas element hasn't actually been mounted anywhere yet, though. So immediately after that, we append the canvas to the <body> element of our html document.
The next line with getBoundingClientRect() [MDN] provides the current dimensions of our canvas. bounds will be an object with the properties top, right, bottom, left, x, y, width, and height. We'll only need those last two properties for the width and height in this chapter.
The final line determines which drawing API we'll be using. Options other than "2d" include:
"webgl"(often used for 3D games and animations, or anything that requires shaders)"webgpu"(many of the same use cases aswebgl, but with a lower-level and newer API, so browser support [caniuse] is limited)"imagebitmaprenderer"(a very specialized tool to get frames rendered by a worker thread efficiently into the main thread's canvas)
We'll be sticking with "2d", which gives us all of the functionality you see in the examples throughout this chapter, including fillRect which you have already used.
You'll also notice the ! non-null assertion at the end of this line. canvas.getContext("2d") can return null ONLY IF the canvas has already been set up for one of the other contexts above. So you can't, for example, change a webgl canvas into a webgpu canvas on the fly. The TypeScript compiler isn't able to statically determine that we won't be doing that, but we know that, so the null case is not a concern.
const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
const bounds = canvas.getBoundingClientRect();
const ctx = canvas.getContext("2d")!;
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, bounds.width, bounds.height); Hello, world!
To begin, draw text with fillText.
fillText takes only a string and position as arguments, but we also want to give it a font and color. Those come from state that is set on ctx before fillText is called. In our example, we're setting the font to "32px sans-serif" and the color to "#3d7ea6" before calling fillText.
ctx.font = "32px sans-serif";
ctx.fillStyle = "#3d7ea6";
ctx.fillText("Hello, world!", 20, 100);
// x yContext2D relies on shared mutable state
Yes, shared mutable state 😱
Any property you set on the context (fillStyle, lineWidth, font, for example) stays set until you change it again. Here, fillRect inherits the same blue fillStyle that colored the text.
ctx.font = "32px sans-serif";
ctx.fillStyle = "#3d7ea6";
ctx.fillText("Hello, world!", 20, 100);
ctx.fillRect(20, 120, 100, 10);
// x y w hThe coordinate system
The two numbers after "Hello, world!" are the x and y coordinates, measured in pixels from the left edge and pixels from the top. y increases downward, unlike the coordinates you learned in school.
ctx.font = "32px sans-serif";
ctx.fillStyle = "#3d7ea6";
ctx.fillText("Hello, world!", 80, 150);
// x yThe z axis
Paint operations run in order, so whatever was drawn last sits on top.
const x = 80;
const y = 150;
ctx.font = "32px sans-serif";
ctx.fillStyle = "#3d7ea6";
ctx.fillText("Hello, world!", x, y);
ctx.fillStyle = "red";
ctx.fillText("Hello, world!", x + 2, y + 2);
ctx.fillStyle = "green";
ctx.fillText("Hello, world!", x + 4, y + 4);
ctx.fillStyle = "orange";
ctx.fillText("Hello, world!", x + 6, y + 6);High-DPI displays
If you've been following along and coding these examples yourself (a great way to learn!) then your canvas probably looks blurry in comparison to the ones you see here. The reason for that is that your screen can handle more pixels than the canvas has at its default pixel density.
A display with a devicePixelRatio of 2 has four physical pixels for every CSS pixel. But by default the canvas doesn't automatically scale itself for high-density displays, resulting in a stretched, blurry image instead.
The standard fix is to add the following boilerplate before your draw code, which we'll cover in depth at the end of this chapter.
const dpr = window.devicePixelRatio;
const { width, height } = bounds;
// set how many pixels exist _within_ the canvas
canvas.width = width * dpr;
canvas.height = height * dpr;
// do some internal canvas scaling
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
// set the number of "css pixels" that
// the canvas occupies in the layout
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
// all drawing code should go after this lineCanvasRenderingContext2D API
Finally, the fun part. Here's a curated cheatsheet with the Context2D functionality that is most relevant to building games.
Paths and shapes
fillRect
As you saw above, use it to draw rectangles.
ctx.fillStyle = "#3d7ea6";
ctx.fillRect(20, 40, 200, 100);
// x y w hstrokeRect
Draw borders around rectangles. The stroke is centered along the edge of the rectangle, so adjust sizing according to lineWidth as needed.
ctx.strokeStyle = "#3d7ea6";
ctx.lineWidth = 5;
ctx.strokeRect(20, 40, 200, 100);
// x y w hDashed lines
Use ctx.setLineDash([length, gap]). Change the dash phase offset like ctx.lineDashOffset = 4 or animate it for a marching ants effect. To reset, pass an empty array: ctx.setLineDash([]). More examples on MDN.
ctx.strokeStyle = "#3d7ea6";
ctx.lineWidth = 5;
ctx.lineDashOffset = 4;
ctx.setLineDash([10, 20]);
// ^ gap size
// ^ dash length
ctx.strokeRect(20, 40, 200, 100);Circles
A circle is just an arc that extends 2π radians. So if you arc from 0 to Math.PI * 2 with some radius, you'll get a circle.
ctx.arc(x, y, radius, startAngle, endAngle)
If you find that you're drawing a lot of circles, ctx.arc is a clunky way to build them each time. A tiny helper function can aid readability.
function circle(ctx, x, y, radius) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fill();
}ctx.strokeStyle = "#3d7ea6";
ctx.lineWidth = 5;
ctx.beginPath();
ctx.arc(80, 100, 40, 0, Math.PI * 2);
// x y r start endAngle
ctx.stroke();
ctx.fillStyle = "#3d7ea6";
ctx.beginPath();
ctx.arc(180, 100, 40, 0, Math.PI * 2);
ctx.fill();Paths
The circle example above introduced a new concept: paths!
You can draw your own shapes with the following path methods:
// various path-related methods:
.(); // start drawing a path
.(, ); // jumps to a new position
.(, ); // draw a line to a coordinate
.(); // line straight back to path origin
.(); // outline the path
.(); // fill the path
// shapes:
.(, , , ); // add rectangle to path
.(, , , , ); // rounded rectangle
.(, , , , , , );
// curved lines:
.(, , , , );
.(, , , , );
.(, , , );
.(, , , , , );function triangle(x: number, y: number, size: number) {
ctx.beginPath();
ctx.moveTo(x, y); // bottom-left
ctx.lineTo(x + size, y); // bottom-right
ctx.lineTo(x, y - size); // top-left
ctx.closePath();
ctx.stroke();
}
ctx.strokeStyle = "#3d7ea6";
ctx.lineWidth = 5;
triangle(50, 150, 100);SVG Paths
Drawing paths with code can be impractical for complex shapes. Thankfully, there is another option. You can use a visual SVG editor to create your path, then save it as an SVG and copy the d value from its <path> element into a new Path2D(d).
ctx.fill() and ctx.stroke() both accept an optional argument where you can pass in this Path2D.
First, convert your shape to a path using Path › Object to Path. Then copy its d attribute from the XML Editor. (Saving the SVG and opening it in a text editor also works.)
Right click any vector layer and select Copy/Paste as › Copy as SVG from
its context menu. Paste the SVG into a text editor and copy the d property from the path.
Select the layer with the path. You can then copy its d attribute from the SVG markup in the
Code tab. (Saving the SVG and opening it in a
text editor also works.)
Save a copy of your shape as SVG, and use Show SVG Code in the SVG options. Then copy the relevant path's d value.
// data copied from some svg file:
const d = `M100 150 C90 140 40 105 40 70 C40 35 80 25 100 55 C120 25 160 35 160 70 C160 105 110 140 100 150 Z`;
const heart = new Path2D(d);
ctx.fillStyle = "#3d7ea6";
ctx.fill(heart);Line joins for rounded corners
By default corners are sharp (lineJoin="miter") but you can round them with lineJoin="round" or bevel them with lineJoin="bevel".
function triangle(x: number, y: number, size: number) {
ctx.beginPath();
ctx.moveTo(x, y); // bottom-left
ctx.lineTo(x + size, y); // bottom-right
ctx.lineTo(x, y - size); // top-left
ctx.closePath();
ctx.stroke();
}
ctx.lineWidth = 15;
ctx.strokeStyle = "seagreen";
triangle(50, 150, 60);
ctx.lineJoin = "round";
ctx.strokeStyle = "coral";
triangle(150, 150, 60);
ctx.lineJoin = "bevel";
ctx.strokeStyle = "mediumpurple";
triangle(250, 150, 60);Line caps
Line caps are used for the ends of a line that are visible when you don't close a path. "square" is similar to the default, "butt", except that it extends the line on each end by half the lineWidth.
const line = (x: number) => {
ctx.beginPath();
ctx.moveTo(x, 50);
ctx.lineTo(x, 130);
ctx.stroke();
};
ctx.lineWidth = 20;
ctx.strokeStyle = "seagreen";
ctx.lineCap = "butt"; // default
line(40);
ctx.strokeStyle = "coral";
ctx.lineCap = "round";
line(100);
ctx.strokeStyle = "mediumpurple";
ctx.lineCap = "square";
line(160);Arcs
While ctx.arc is commonly used for circles, it can also be useful for progress indicators.
ctx.arc(x, y, radius, startAngle, endAngle)
ctx.strokeStyle = "#3d7ea6";
ctx.lineWidth = 5;
ctx.beginPath();
ctx.arc(80, 100, 40, Math.PI, Math.PI / 2);
ctx.stroke();Text
Fill text
Let's return to our hello world example.
ctx.font = "50px sans-serif";
ctx.fillStyle = "#3d7ea6";
ctx.fillText("Hello, world!", 50, 100);Stroke text
Like many of the other fill* APIs, there's a stroke equivalent for text.
ctx.font = "50px sans-serif";
ctx.strokeStyle = "#3d7ea6";
ctx.lineWidth = 2;
ctx.strokeText("Hello, world!", 50, 100);Measuring text
Typography enthusiasts should be excited to learn that you can read many font metrics directly with ctx.measureText("..."). Unfortunately, some metrics such as emHeightAscent cannot currently be used due to poor browser support [caniuse].
measureText returns...
fontBoundingBoxAscent- How many px above the baseline the tallest letter (or highest ascender) can possibly go font-wide (for any text)fontBoundingBoxDescent- How many px below the baseline the lowest descender goes font-wideactualBoundingBoxAscent- For the specific text being measured, how many px above the baseline does it goactualBoundingBoxDescent- For the specific text being measured, how many px below the baseline do descenders goactualBoundingBoxLeftandactualBoundingBoxRight- Distances from the origin to each edge. When you draw text starting at somexorigin, the actual characters can be drawn to the left or the right of it depending on thetextAlignand whether they're italicized.actualBoundingBoxLeftandactualBoundingBoxRightgive you the distance fromxto the true left (or right) edge.width- Confusingly, is not the sum ofactualBoundingBoxLeft + actualBoundingBoxRight.widthrefers to the number of pixels that a cursor would advance when typing the measured text. Each glyph has an "advance" value, andwidthis their sum which also takes into account kerning. Another way to think about this is that it is the right property to use for a cursor if you're implementing a text editor because it's a layout value, not a precise measurement of the pixels of the text.- some additional properties:
emHeightAscent/emHeightDescentthat aren't widely supported but measure the distance to the top and bottom of the letterM, andideographicBaseline/hangingBaselinetypically for internationalization.
ctx.fillStyle = "#3d7ea6";
ctx.font = "30px sans-serif";
const {
actualBoundingBoxAscent,
actualBoundingBoxLeft,
actualBoundingBoxRight,
fontBoundingBoxAscent,
width,
} = ctx.measureText("Hello, world!");
const x = 50;
const y = 80;
ctx.fillText("Hello, world!", x, y);
ctx.fillText(`width: ${width}`, x, y + 50);Text alignment
By default text is expected to be aligned to the bottom-left. However, you can see that the descenders of the comma and letter g are clipped. Using the right vertical alignment can fix this.
const { height } = bounds;
ctx.font = "50px sans-serif";
ctx.fillStyle = "#3d7ea6";
ctx.fillText("Hello, gamer", 0, height);Vertical alignment
Use textBaseline for vertical alignment.
const baselines = [
"top",
"middle",
"bottom",
"alphabetic", // the default
] as const;
ctx.font = "24px sans-serif";
for (const [i, baseline] of baselines.entries()) {
const y = i * 50;
ctx.fillStyle = "seagreen";
ctx.lineWidth = 1;
ctx.fillRect(0, y, bounds.width, 1); // 1px line
ctx.fillStyle = "#3d7ea6";
ctx.textBaseline = baseline;
ctx.fillText(`${baseline}: Hello, gamer`, 20, y);
}Horizontal alignment
Use textAlign for horizontal alignment. Possible values are left/right/center/start/end. The default is start, which maps to left in left-to-right locales and maps to right in right-to-left locales.
const { width, height } = bounds;
const cy = height / 2;
const cx = width / 2;
ctx.textBaseline = "middle";
ctx.font = "30px sans-serif";
ctx.fillStyle = "#3d7ea6";
ctx.textAlign = "left";
ctx.fillText("Left", 0, cy);
ctx.textAlign = "center";
ctx.fillText("Center", cx, cy);
ctx.textAlign = "right";
ctx.fillText("Right", width, cy);Font weights, italics, families
You can specify these properties (and others [MDN]) in the ctx.font as well.
ctx.font = `italic small-caps bold 32px serif`;
ctx.fillStyle = "#3d7ea6";
ctx.fillText("Hello, world!", 50, 50);Custom fonts
You have a few options:
- Download a font and use
@font-facein CSS [MDN], allowing the browser to decide when it loads and whether to show a fallback during loading.
Option 1 deep-dive
Option 1 requires that we return to the index.html from Chapter 1. For this example we'll use the variable font Doto.
One benefit to option 1 over option 3 is that the font can start downloading even before your JavaScript bundle is parsed by the browser, as long as it's also applied to some text outside of your canvas. (You have to trick the browser by creating a hidden text element that uses it.) On the other hand, the main trade-off with this approach is that you'll sometimes see a brief flash of text in a fallback font before the font has loaded, especially on the first visit.
Even if you change font-display: swap to font-display: block, browsers will often still briefly display a fallback font, especially to users with slower internet. font-display is a hint to the browser, not an instruction.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Your Game</title>
<style>
@font-face {
font-family: "Doto";
font-style: normal;
font-weight: 100 900; /* range of weights */
font-display: swap;
src: url(/fonts/doto.ttf) format("truetype");
}
p {
color: transparent;
font-family: "Doto";
}
canvas {
position: fixed;
inset: 0;
}
</style>
</head>
<body>
<p>Hidden text to trick the browser into downloading the font asap</p>
<script type="module" src="/src/main.ts"></script>
</body>
</html>- Use a service that does (1) for you, like Google Fonts. (Don't do this.)
Why not?
Creating a dependency on a third party service can be tempting when it offers convenience, but this has downsides. First of all, you now require the service to always host your font at this exact URL. Suppose Google is no longer licensed to serve your game's font. Or perhaps they decide to charge for this service at some point. Or maybe someday their servers have downtime. Because the font is not a part of your game's bundle, in any of these scenarios you're simply out of luck. We want to guarantee that your game is playable with all of its fonts 20 or even 100 years from now.
The cross-site network request also complicates things when we work on preparing your game to work offline. Self-hosting your fonts and other assets makes offline mode dead simple.
For these and many other reasons, option 2 is a poor choice.
- For precise control over the timing of the loading of your font, download it and load with JavaScript. This is typically a solid choice for games, so it's our pick in this guide, but it does load the font sequentially after the JavaScript bundle has been parsed, rather than taking advantage of parallel loading like option 1.
To load a custom font in JavaScript, you'll first need to download a font file (typically .ttf, .otf, or .woff2) from a source like Google Fonts or itch.io. If you have a choice, woff2 is usually preferred for its smaller file sizes.
You'll then asynchronously load the font. See MDN for explanations of the global FontFace constructor and document.fonts.add.
// import dotoFont from './assets/doto.ttf';
const fontFace = new FontFace(
"doto", // the name you'll use in ctx.font
`url(${dotoFont})`,
);
document.fonts.add(fontFace);
ctx.font = `100px doto`;
ctx.fillStyle = "#3d7ea6";
ctx.fillText("Doto!", 50, 120);Async font loading
Although the previous code works, you'll probably see a flash of unstyled text (FOUT) in a fallback font while the custom font initially loads.
One option is to simply render nothing until the font has loaded. You can decide for your project whether a fallback font or no text at all while it loads feels better.
One way to make these loading states invisible to users is to make the text on your first screen a lightweight image inlined into your bundle, and display that while your custom fonts load in the background.
// import dotoFont from './assets/doto.ttf';
const fontFace = new FontFace(
"doto", // the name you'll use in ctx.font
`url(${dotoFont})`,
);
fontFace.load().then(() => {
document.fonts.add(fontFace);
ctx.font = `100px doto`;
ctx.fillStyle = "#3d7ea6";
ctx.fillText("Doto!", 50, 120);
});Opacity and blending
Opacity using colors with alpha
fillStyle and strokeStyle accept a wide variety of color formats. Many of these support an Alpha channel, which you can use to control the opacity of whatever you are painting.
ctx.fillStyle = "#3d7ea680";
// rrggbbaa
ctx.fillRect(20, 15, 100, 100);
ctx.fillRect(70, 65, 100, 100);
ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
// r g b a
ctx.fillRect(0, 50, 100, 40);
ctx.fillStyle = "oklch(83% 0.19 84 / 0.3)";
// L C hue alpha
ctx.fillRect(70, 50, 150, 40);
// wow, artOpacity using globalAlpha
Often, simply using colors with an alpha channel for opacity won't be sufficient.
Fading in and out an image asset is one case where that approach breaks down.
Coordinating translucency changes across many different shapes, especially during a fade animation, is another example where the previous technique would be a pain.
For these and many other uses, we have globalAlpha.
ctx.fillStyle = "#3d7ea6";
ctx.strokeStyle = "#3d7ea6";
ctx.lineWidth = 2;
// globalAlpha is still 1 here,
// so this is fully opaque
ctx.fillRect(20, 15, 100, 100);
// x y w h
ctx.globalAlpha = 0.5;
ctx.fillRect(70, 65, 100, 100); // 50% opacity
ctx.strokeRect(150, 45, 40, 40); // 50% opacity
ctx.globalAlpha = 1; // remember to restore it!Save and restore stack
You can save the full state of the Context2D at any time with ctx.save(), then restore it with ctx.restore().
Why do this?
Subtle bugs can arise when you mutate the shared state in the canvas Context2D. Imagine that you have ctx.lineWidth = 5 deep within some nested function call. Then you call that function in another place and suddenly a bunch of unrelated shapes which had expected to inherit a different lineWidth are now incorrectly using 5.
A clunky solution to this might be to collect the "before" values for every property that is updated. Then change those properties, execute the paint, and restore each one back to its original value. When you're doing that potentially thousands of times across your code, this approach becomes a burden. Thankfully, we have a much more elegant option.
Enter save() and restore().
ctx.save() takes a snapshot of the entire current state of the context and pushes it onto a stack. ctx.restore() pops the top item off of this state stack and restores the values back to what they were at the time of the snapshot being saved.
You can save and restore multiple times and in any order. Just remember—like closing your parentheses in code—the number of ctx.save() calls MUST equal the number of ctx.restore() calls by the end of each animation frame or you'll run into problems.
ctx.fillStyle = "#3d7ea6";
ctx.save();
// temporarily change a bunch of state
ctx.fillStyle = "green";
ctx.globalAlpha = 0.5;
ctx.translate(110, 25);
ctx.scale(1.5, 1);
ctx.fillRect(40, 40, 100, 100);
// back to how things were before .save()
ctx.restore();
ctx.fillRect(40, 40, 100, 100);Images
drawImage
ctx.drawImage(image, x, y) [MDN] paints an image with its top-left corner at (x, y) drawn at its intrinsic size.
Just like fonts, images load asynchronously as soon as src is set. If you want to show a spinner while waiting until the image can be shown, you can await its decode promise, which resolves not just after the image has loaded, but after the bitmap is in memory and ready to be rendered.
async function (: string) {
const = new ();
. = ;
await .();
return ;
}Pixel art image credit: ansimuz
// import imgUrl from './assets/example.png';
// const image = new Image();
// image.src = imgUrl;
ctx.drawImage(image, 0, 0); drawImage with destination rectangle
The same drawImage method has another form that accepts a destination width and height. The entire image is mapped onto the rectangle defined by (x, y, width, height), so the original aspect ratio is ignored.
ctx.drawImage(image, x, y, width, height);const { width, height } = bounds;
// entire bitmap stretched into this rectangle
ctx.drawImage(image, 0, 0, width, height);drawImage with source crop and scale
The third, final form that drawImage supports uses nine arguments to crop according to a source rectangle then scale and draw according to a destination rectangle. This is super useful for spritesheets.
Nine-argument function calls are a lot to look at, so the key is to think of the two rectangles separately:
- The source rectangle
(sx, sy, sw, sh)(in image pixels) defines which parts of the source image to use. - The destination rectangle
(x, y, w, h)(on the canvas) defines where to paint the source image.
const source = { x: 200, y: 0, w: 150, h: 97 };
const dest = {
x: 0,
y: 0,
w: bounds.width,
h: bounds.height,
};
ctx.drawImage(
// source bitmap
image,
// source rectangle
source.x,
source.y,
source.w,
source.h,
// destination rectangle
dest.x,
dest.y,
dest.w,
dest.h,
);Image scaling option 1: contain
To contain the full image within the canvas (like object-fit: contain [MDN]), figure out whether the height or width will be the smaller factor, then scale uniformly according to that factor and center the image. Since we're drawing the entire source image, we only need the five-argument form of drawImage.
const { width, height } = bounds;
const nw = image.naturalWidth;
const nh = image.naturalHeight;
const scale = Math.min(
width / nw, // smaller for this image
height / nh,
);
const w = nw * scale;
const h = nh * scale;
const x = (width - w) / 2;
const y = (height - h) / 2; // centered
ctx.drawImage(image, x, y, w, h);Image scaling option 2: cover
For object-fit: cover behavior, figure out which dimension needs the larger scale factor, then derive the crop dimensions. The source rect starts at (0, 0), so extra pixels are chopped off the right or bottom edges.
This requires the nine-argument drawImage function signature.
Center-based origin for object-fit: cover
Instead of lopping off pixels from just the bottom/right, you can anchor based on the center of the image with the following code.
import imageUrl from "./assets/example.png";
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d")!;
const image = new Image();
image.src = imageUrl;
const bounds = canvas.getBoundingClientRect();
const { width, height } = bounds;
const nw = image.naturalWidth;
const nh = image.naturalHeight;
const scale = Math.max(width / nw, height / nh);
const sw = width / scale;
const sh = height / scale;
const sx = (nw - sw) / 2;
const sy = (nh - sh) / 2;
const source = { x: sx, y: sy, w: sw, h: sh };
const dest = { x: 0, y: 0, w: width, h: height };
ctx.drawImage(
image, // source bitmap
source.x,
source.y,
source.w,
source.h,
dest.x,
dest.y,
dest.w,
dest.h,
);const { width, height } = bounds;
const nw = image.naturalWidth;
const nh = image.naturalHeight;
const scale = Math.max(width / nw, height / nh);
const sw = width / scale;
const sh = height / scale;
const source = { x: 0, y: 0, w: sw, h: sh };
const dest = { x: 0, y: 0, w: width, h: height };
ctx.drawImage(
image, // source bitmap
source.x,
source.y,
source.w,
source.h,
dest.x,
dest.y,
dest.w,
dest.h,
);Crisp pixels for pixel art
The pixel art in the previous demo looks bad! To scale images up sharply, you'll also need to set ctx.imageSmoothingEnabled = false to disable antialiasing.