26 lines
1.1 KiB
JavaScript
26 lines
1.1 KiB
JavaScript
'use strict';
|
|
const patterns = new WeakMap();
|
|
|
|
// Called with the same world-to-canvas transform used to draw the skeleton.
|
|
function drawCheckerboard(ctx, width, height) {
|
|
let pattern = patterns.get(ctx);
|
|
if (!pattern) {
|
|
const tile = ctx.canvas.ownerDocument.createElement('canvas');
|
|
tile.width = tile.height = 100;
|
|
const paint = tile.getContext('2d');
|
|
paint.fillStyle = '#505052'; paint.fillRect(0, 0, 100, 100);
|
|
paint.fillStyle = '#5a5a5c'; paint.fillRect(0, 0, 50, 50); paint.fillRect(50, 50, 50, 50);
|
|
pattern = ctx.createPattern(tile, 'repeat'); patterns.set(ctx, pattern);
|
|
}
|
|
const m = ctx.getTransform().inverse();
|
|
const corners = [[0,0], [width,0], [width,height], [0,height]].map(([x,y]) => [m.a*x+m.c*y+m.e, m.b*x+m.d*y+m.f]);
|
|
const xs = corners.map(p => p[0]), ys = corners.map(p => p[1]);
|
|
const x = Math.min(...xs), y = Math.min(...ys);
|
|
if (!Number.isFinite(x + y)) return;
|
|
ctx.save();
|
|
try { ctx.imageSmoothingEnabled = false; ctx.fillStyle = pattern; ctx.fillRect(x, y, Math.max(...xs)-x, Math.max(...ys)-y); }
|
|
finally { ctx.restore(); }
|
|
}
|
|
|
|
module.exports = { drawCheckerboard };
|