Skip to content

Commit 4fe9a6b

Browse files
committed
feat(CanvasContext): Added optional devicePixelRatio argument to resize
It's mainly useful in context of rendering in web worker, because web worker doesn't have access to devicePixelRatio, so resize code will be split between 1. main thread asking for a render, providing devicePixelRatio 2. Worker rendering and resizing CanvasContext w/ provided ratio 3. Worker giving back main thread the resize target 4. Main thread applying css width/height provided by the worker
1 parent a12ddc6 commit 4fe9a6b

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

src/canvascontext.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -169,19 +169,19 @@ export class CanvasContext extends RenderContext {
169169
return this;
170170
}
171171

172-
resize(width: number, height: number): this {
172+
resize(width: number, height: number, devicePixelRatio?: number): this {
173173
const canvas = this.context2D.canvas;
174-
const devicePixelRatio = globalObject().devicePixelRatio || 1;
174+
const dpr: number = devicePixelRatio ?? globalObject().devicePixelRatio ?? 1;
175175

176176
// Scale the canvas size by the device pixel ratio clamping to the maximum supported size.
177-
[width, height] = CanvasContext.sanitizeCanvasDims(width * devicePixelRatio, height * devicePixelRatio);
177+
[width, height] = CanvasContext.sanitizeCanvasDims(width * dpr, height * dpr);
178178

179179
// Divide back down by the pixel ratio and convert to integers.
180-
width = (width / devicePixelRatio) | 0;
181-
height = (height / devicePixelRatio) | 0;
180+
width = (width / dpr) | 0;
181+
height = (height / dpr) | 0;
182182

183-
canvas.width = width * devicePixelRatio;
184-
canvas.height = height * devicePixelRatio;
183+
canvas.width = width * dpr;
184+
canvas.height = height * dpr;
185185

186186
// The canvas could be an instance of either HTMLCanvasElement or an OffscreenCanvas.
187187
// Only HTMLCanvasElement has a style attribute.
@@ -190,7 +190,7 @@ export class CanvasContext extends RenderContext {
190190
canvas.style.height = height + 'px';
191191
}
192192

193-
return this.scale(devicePixelRatio, devicePixelRatio);
193+
return this.scale(dpr, dpr);
194194
}
195195

196196
rect(x: number, y: number, width: number, height: number): this {

0 commit comments

Comments
 (0)