From 5f235f4c1c01b3b545e93ea36921d14f34bb92e2 Mon Sep 17 00:00:00 2001 From: Jukka Kurkela Date: Tue, 24 Nov 2026 05:32:10 +0200 Subject: [PATCH] fix: compare charts drawn on an OffscreenCanvas toEqualImageData accepted only a CanvasRenderingContext2D, an HTMLCanvasElement or a chart whose context was one, so a chart acquired with `useOffscreenCanvas: true` failed with "Input value is not a valid image source." before any pixel was compared. 0.x checked `instanceof Chart` and passed such charts on. toBeValidChart rejected them as well. Both matchers now also accept an OffscreenCanvas and its OffscreenCanvasRenderingContext2D, recognised by their tags so that a browser without OffscreenCanvas does not throw. Updating a reference image copies an OffscreenCanvas onto a plain canvas first, since it has no toDataURL. --- README.md | 6 +++++ src/fixtures.js | 18 ++++++++++++-- src/matchers.js | 32 ++++++++++++++++++------- test/fixtures/basic/bar-offscreen.json | 27 +++++++++++++++++++++ test/fixtures/basic/bar-offscreen.png | Bin 0 -> 805 bytes test/specs/utils.spec.js | 18 ++++++++++++++ 6 files changed, 90 insertions(+), 11 deletions(-) create mode 100644 test/fixtures/basic/bar-offscreen.json create mode 100644 test/fixtures/basic/bar-offscreen.png diff --git a/README.md b/README.md index d709006..a71a25e 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,12 @@ means accepting that the output changed. | `toBeCloseToPoint({x, y})` | rounded to two decimals | | `toEqualOneOf([...])` | value is one of the expected | +Both `toEqualImageData` and `toBeValidChart` accept a chart drawn on an +`OffscreenCanvas` (`acquireChart(config, {useOffscreenCanvas: true})`), and +`toEqualImageData` also takes the canvas or the 2d context directly. Chromium +rasterizes an `OffscreenCanvas` slightly differently from an onscreen canvas, so +an offscreen fixture needs a reference image of its own. + `toEqualImageData` takes `threshold` (per-pixel color distance) and `tolerance` (accepted ratio of differing pixels). It blends transparency against white: pixelmatch 7.2.0 made checkerboard blending the default, which is a different diff --git a/src/fixtures.js b/src/fixtures.js index 94fcab7..b145fe8 100644 --- a/src/fixtures.js +++ b/src/fixtures.js @@ -8,7 +8,7 @@ * here rather than produced here. */ import {expect, it} from 'vitest'; -import {readImageData} from './canvas.js'; +import {createCanvas, readImageData} from './canvas.js'; import {acquireChart, releaseChart} from './chart.js'; import {toEqualImageData} from './matchers.js'; @@ -76,7 +76,21 @@ async function compareOrSave(chart, name, inputs, json, save) { if (expected && toEqualImageData(chart, expected, json).pass) { return; } - await save(name, chart.ctx.canvas.toDataURL()); + await save(name, toDataURL(chart.ctx.canvas)); +} + +/** + * An OffscreenCanvas has no `toDataURL`, so its pixels are copied onto a plain + * canvas first. `drawImage` copies them as they are, without the round trip + * through unpremultiplied `ImageData` that would change semi-transparent ones. + */ +function toDataURL(canvas) { + if (typeof canvas.toDataURL === 'function') { + return canvas.toDataURL(); + } + const copy = createCanvas(canvas.width, canvas.height); + copy.getContext('2d').drawImage(canvas, 0, 0); + return copy.toDataURL(); } function specFromFixture(name, inputs) { diff --git a/src/matchers.js b/src/matchers.js index 8d765c4..9f60aa9 100644 --- a/src/matchers.js +++ b/src/matchers.js @@ -16,17 +16,31 @@ function toPercent(value) { return Math.round(value * 10000) / 100; } +// `acquireChart(config, {useOffscreenCanvas: true})` draws on an OffscreenCanvas, +// whose canvas and context are classes of their own. They are compared by tag +// rather than `instanceof`, so a browser without OffscreenCanvas does not throw. +const CANVAS_TAGS = ['[object HTMLCanvasElement]', '[object OffscreenCanvas]']; +const CONTEXT_TAGS = ['[object CanvasRenderingContext2D]', '[object OffscreenCanvasRenderingContext2D]']; + +function isCanvas(value) { + return CANVAS_TAGS.includes(Object.prototype.toString.call(value)); +} + +function isContext(value) { + return CONTEXT_TAGS.includes(Object.prototype.toString.call(value)); +} + function resolveContext(actual) { - if (actual instanceof CanvasRenderingContext2D) { + if (isContext(actual)) { return actual; } - if (actual instanceof HTMLCanvasElement) { + if (isCanvas(actual)) { return actual.getContext('2d'); } // A Chart instance. `instanceof Chart` only works when the consumer and the - // chart under test resolve to the same chart.js copy, the canvas check does + // chart under test resolve to the same chart.js copy, the context check does // not care. - return actual?.ctx instanceof CanvasRenderingContext2D ? actual.ctx : null; + return isContext(actual?.ctx) ? actual.ctx : null; } /** @@ -84,10 +98,10 @@ export function toBeValidChart(actual) { if (Chart && !(actual instanceof Chart)) { message = `Expected ${actual} to be an instance of Chart`; - } else if (Object.prototype.toString.call(actual.canvas) !== '[object HTMLCanvasElement]') { - message = 'Expected canvas to be an instance of HTMLCanvasElement'; - } else if (Object.prototype.toString.call(actual.ctx) !== '[object CanvasRenderingContext2D]') { - message = 'Expected context to be an instance of CanvasRenderingContext2D'; + } else if (!isCanvas(actual.canvas)) { + message = 'Expected canvas to be an instance of HTMLCanvasElement or OffscreenCanvas'; + } else if (!isContext(actual.ctx)) { + message = 'Expected context to be an instance of CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D'; } else if (typeof actual.height !== 'number' || !isFinite(actual.height)) { message = 'Expected height to be a strict finite number'; } else if (typeof actual.width !== 'number' || !isFinite(actual.width)) { @@ -143,7 +157,7 @@ export function toBeChartOfSize(actual, expected) { /** * Compares a rendered canvas against a reference image. - * @param {object} actual - a Chart, a canvas or a 2d context + * @param {object} actual - a Chart, a canvas or a 2d context, onscreen or offscreen * @param {ImageData} [expected] - the reference image data * @param {object} [opts] - comparison options * @param {number} [opts.threshold] - per pixel color distance, see pixelmatch diff --git a/test/fixtures/basic/bar-offscreen.json b/test/fixtures/basic/bar-offscreen.json new file mode 100644 index 0000000..10985b7 --- /dev/null +++ b/test/fixtures/basic/bar-offscreen.json @@ -0,0 +1,27 @@ +{ + "description": "bar chart on an OffscreenCanvas, which Chromium rasterizes slightly differently from bar.json", + "config": { + "type": "bar", + "data": { + "labels": ["a", "b", "c"], + "datasets": [ + { + "data": [3, 1, 2], + "backgroundColor": "#36a2eb", + "borderColor": "#1c6ea4", + "borderWidth": 2 + } + ] + }, + "options": { + "scales": { + "x": { "display": false }, + "y": { "display": false, "beginAtZero": true } + } + } + }, + "options": { + "canvas": { "height": 256, "width": 256 }, + "useOffscreenCanvas": true + } +} diff --git a/test/fixtures/basic/bar-offscreen.png b/test/fixtures/basic/bar-offscreen.png new file mode 100644 index 0000000000000000000000000000000000000000..c56a5be4fcfb43a0e698d0568ea582a1b01f2e29 GIT binary patch literal 805 zcmeAS@N?(olHy`uVBq!ia0y~yU<5K5893O0R7}x|GzJEyH=ZtzAr-gYUf=I^*n#2r z$K7g6Ztxwf_we2}DYSV<_hkRc`=(TK+?Bbr>%}Vng-s8VmUMLFu`Vq5S@WQre*$;> zj=&oMTi^UzsOzxE&5n`dK-#81rFCVJLHA3x?fBfSz|a7+gMovALI%YKVA@Z>$PK2U z)uq;3I2mfXKh_ioGyE{TH-BwkpZ>exc==7{{tQ1BOZea0yeK0mzT=}aC{S4#1Q;A( z3?wF8j6w!YjNG;=YxnG|n_ruwZpZGfWPISg-|my=&xk4Q{F?grHRs1{XZR2uBVS$m xxhP=%yd`_??y4-iOG { expect(createMockContext()).not.toEqualImageData(undefined); }); }); + +describe('charts on an OffscreenCanvas', () => { + it('should be valid charts', (ctx) => { + const chart = barChart({canvas: {height: 128, width: 256}, useOffscreenCanvas: true}, ctx); + + expect(chart).toBeValidChart(); + expect(chart.ctx).toBeInstanceOf(OffscreenCanvasRenderingContext2D); + }); + + it('should compare as a chart, a canvas and a context', (ctx) => { + const chart = barChart({canvas: {height: 128, width: 256}, useOffscreenCanvas: true}, ctx); + const expected = chart.ctx.getImageData(0, 0, 256, 128); + + expect(chart).toEqualImageData(expected); + expect(chart.canvas).toEqualImageData(expected); + expect(chart.ctx).toEqualImageData(expected); + }); +});