JavaScript / Canvas based imagediff utility.
-
createCanvas()create a new Canvas element. -
createImageData(width, height)create a new ImageData object. -
isImage(object)tests for Image object. -
isCanvas(object)tests for Canvas object. -
isContext(object)tests for CanvasRenderingContext2D object. -
isImageData(object)tests for ImageData object. -
isImageType(object)tests for any of the above. -
toImageData(object)converts image type object to a new ImageData object. -
equal(a, b, tolerance)tests image type objects for equality. Without a tolerance the images must match exactly. The tolerance is either:- a number: the largest difference allowed in any channel of any pixel, from 0 to 255;
- or an options object, with either or both of these limits, each a fraction (0 to 1) of 255. Only the limits given apply (an option that isn't a number, or is misspelled, is ignored), and with neither the images must match exactly.
maxPixelDifference: the largest difference allowed in any channel of any pixel.{ maxPixelDifference: 10 / 255 }is the same as10.maxAverageDifference: the largest average difference across all channels of all pixels. Alpha is included, so in opaque images the color channels may average up to a third more.
For example,
imagediff.equal(a, b, { maxPixelDifference: 0.05, maxAverageDifference: 0.01 })allows no channel more than 5% off, and the image no more than 1% off overall. -
diff(a, b, options)performs an image diff on a and b, returning a - b.options.alignset to'top'to top-align the images when diffing different sizes.
-
recordFailures(record)starts (true) or stops (false) recording the images of failedtoImageDiffEqualexpectations, for a test reporter to show. Stopping drops what is recorded. Returns whether it was recording. Off by default. -
takeFailures()returns the failures recorded since the last call, as{ actual, expected, tolerance }objects with copies of the images as ImageData, and clears them. One reporter at a time should take the record. -
noConflict()removes imagediff from the global space for compatibility, returning imagediff. -
imageDataToPNG(imageData, outputFile, [callback])(node only) renders the imageData to png in outputFile with optional callback.
js-imagediff is available through npm and needs Node.js 18.12 or later on the 18 line, or 20.9 or later (^18.12.0 || >=20.9.0, as node-canvas 3 does). In Node.js it draws with node-canvas 3, an optional dependency that installs from prebuilt binaries on common platforms; elsewhere it builds from source, which needs Cairo and the other libraries listed in the node-canvas installation guide.
Install the library with npm install imagediff and load it with require('imagediff'), or install the command line tool with npm install -g imagediff.
imagediff [-e|--equal] [-t|--tolerance VALUE] FILE_A FILE_Btests equality of two image files with an optional tolerance, printingtrueorfalseand exiting with status 0 or 1.imagediff [-d|--diff] FILE_A FILE_B OUTPUT_FILErenders an imagediff between two files, saving it as a PNG in the output file.
Canvas is an optional dependency for better browser and bundler support, so the library loads without it and reports this error when it first needs a canvas. If you see it in Node.js, check the output of npm install, in case node-canvas failed to install. This relates to #22.
JS ImageDiff opens up the easy testing of Canvas and other image-like objects in JavaScript. js-imagediff supplies two Jasmine matchers to make this easier.
toImageDiffEqual(expected, tolerance)expect a result to equal another image type, with an optional tolerance as forequal.toBeImageData()expect a result to be ImageData.
The matchers work with Jasmine 2.0 and later. To see how two images differ, render imagediff.diff(actual, expected) to a canvas, or save it with imagediff.imageDataToPNG() in Node.js.
To use matchers:
beforeEach(function () {
jasmine.addMatchers(imagediff.jasmine);
});
it('draws the expected image', function () {
expect(canvas).toImageDiffEqual(expectedImage, 2);
});To see the actual, expected and diff images under each failed toImageDiffEqual in Jasmine's HTML report, load the Jasmine add-on, imagediff-jasmine.js (or imagediff-jasmine.min.js), after imagediff itself:
<script src="imagediff.js"></script>
<script src="imagediff-jasmine.js"></script>Then add its reporter, once, before the specs run:
jasmine.getEnv().addReporter(imagediffJasmine.reporter);The add-on doesn't change imagediff or its matchers. Its reporter turns on imagediff's failure record (recordFailures) while a run has an HTML report, and draws what it takes from it. Failure messages stay plain text for every other reporter.
With a bundler, require('imagediff/imagediff-jasmine').reporter is the reporter. With AMD, the add-on asks for the module imagediff, so map that id to imagediff (for example with a RequireJS paths entry). The reporter needs Jasmine 3.0 or later.
A demo is available at https://humblesoftware.github.io/js-imagediff/, and the same example is in examples/ in this repository.
- Flotr2 - unit testing
- Envision.js - unit testing
- CSS Critic - A CSS regression testing framework
- HSLuv (formerly HUSL) - used for regression testing before release.
- SUCCSS - CSS regression testing.
- Origami.js - A canvas library
If you are using js-imagediff please drop us a line and let us know what you are doing with it.
Commit messages and PR titles follow Conventional Commits; see CONTRIBUTING.md.
Use the Node version in .nvmrc, then:
npm ci
npx playwright install --with-deps chromium # one-time
npm testnpm testruns the specs in Node.js and then in headless Chromium, and fails if either fails. The specs and the CLI use the source injs/, so no build is needed first.npm run test:noderuns the specs, including a smoke test of theimagediffCLI, in Node.js against node-canvas (the optionalcanvasdependency, whichnpm ciinstalls from prebuilt binaries on common platforms).npm run test:browserruns the specs in headless Chromium with Playwright.npm run test:serveserves the specs at http://localhost:8085/spec/ to watch them run in a browser. http://localhost:8085/spec/reporter/ runs specs that fail on purpose, to show what the Jasmine add-on's reporter draws.IMAGEDIFF_LIBRARY=imagediff.min.js npm testruns the same specs against a built file (a path from the repository root) instead of the source: throughrequirein Node and as a<script>global in Chromium. The add-on specs load the add-on built next to it (imagediff-jasmine.min.jswithimagediff.min.js).npm run test:builtdoes this forimagediff.jsand thenimagediff.min.js.npm run releasebuilds the release files and then runsnpm run test:built, leaving them ready to commit.npm publishrunsnpm run test:builtfirst (without rebuilding) and refuses to publish if it fails or if the built files differ from what's committed. See CONTRIBUTING.md.npm run build(ormake imagediff) writesimagediff.js(a license header naming thepackage.jsonversion +js/imagediff.js) andimagediff.min.js, and the same for the Jasmine add-on (imagediff-jasmine.jsandimagediff-jasmine.min.js, fromjs/imagediff-jasmine.js), minified with terser to ES5 output. Run it only when preparing a release; see CONTRIBUTING.md.
The repo includes an optional dev container with Node, Chromium and its system libraries ready to go, so only Podman or Docker is needed. Open the repo in VS Code or Codespaces, or run devcontainer up --workspace-folder ., and dependencies are installed with npm ci; then npm test works as above. Working without the container is still supported.
The container uses the official Playwright image, whose tag in .devcontainer/devcontainer.json must match the @playwright/test version in package-lock.json. Bump the tag whenever Playwright is upgraded. CI (.github/workflows/test.yml) reads the image from the same file, so it needs no separate change.
- A Jasmine add-on,
imagediff-jasmine.js, shows the actual, expected and diff images of a failedtoImageDiffEqualin Jasmine's HTML report, as 1.0.8 did. Load it after imagediff and add its reporter withjasmine.getEnv().addReporter(imagediffJasmine.reporter). recordFailures()andtakeFailures()keep the images of failedtoImageDiffEqualexpectations for a test reporter to show. Recording is off unless a reporter turns it on.not.toImageDiffEqualuses its own comparison (negativeCompare), so its failures are recorded too. Its results and messages are unchanged.equalandtoImageDiffEqualtake an options object as the tolerance, to limit the average difference across the whole image (maxAverageDifference), the difference in any channel (maxPixelDifference), or both (#126).
Breaking changes:
- Node.js
^18.12.0 || >=20.9.0is required, and the optionalcanvasdependency is node-canvas 3 (was 1.x). - The Jasmine matchers use the Jasmine 2.0+ API: add them with
jasmine.addMatchers(imagediff.jasmine). Jasmine 1 (this.addMatchers) is no longer supported. toImageDiffEqualfailure messages are plain text in browsers, as in Node.js, instead of HTML with the actual, expected and diff images.- The Bower package (
bower.json) is removed; install from npm. - The npm package contains only the library, the CLI and their license and docs.
Other changes:
- The library loads without a canvas implementation (in bundlers, or in Node.js without
canvas) and reports the missing module when first used. - The library loads in bundlers that wrap modules in strict mode, and AMD
definereceives the module. - The matchers are tested on Jasmine 7.
- The built files' header names the package version.
- The repository's default branch is
main(wasmaster).
- Update canvas dependency.
- Expose internal Canvas.
- Add async image loading for canvas (closes #31, #35, #39).
- Support
--diff,--equal,--tolerance(closes #17).
- Add top-aligned diffing option.
- Fix issue with diffing transparencies.
- Move canvas to optional dependencies for browserify support.
- Updated canvas dependency.
- Add check for arguments count in diff mode.
- Added NPM/node.js support.
- Added command line interface for
equalanddiffmethods. - Added
imageDataToPNGmethod for node environments. - Added tolerance to handle lossy formats and provide option for acceptable difference.
- Added optional width / height parameters to
createCanvasfor symmetry withcreateImageData. - Fixed issue with
toImageDiffEqual()matcher and non Node types - will no convert ImageData and contexts to Canvas elements for display.
- Moved library to imagediff.js
- Added Jasmine matchers
- Minor bug fixes, lint fixes.
Carl Sutherland carl@humblesoftware.com http://www.humblesoftware.com