Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 16 additions & 2 deletions src/fixtures.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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) {
Expand Down
32 changes: 23 additions & 9 deletions src/matchers.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions test/fixtures/basic/bar-offscreen.json
Original file line number Diff line number Diff line change
@@ -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
}
}
Binary file added test/fixtures/basic/bar-offscreen.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
18 changes: 18 additions & 0 deletions test/specs/utils.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,21 @@ describe('matchers', () => {
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);
});
});