Get started with pixelmatch CDN

ISC licensed

Pixelmatch: Library for precise pixel-level image comparison and measurement.

Tags:
  • image
  • comparison
  • diff

Stable version

Copied!

How to start using pixelmatch CDN


// Include the pixelmatch library from the CDN
const PixelMatcher = require('pixelmatch-js/dist/index.js');

// Define the source and reference images
const sourceImage = new Image();
sourceImage.src = 'path/to/source-image.png';

const referenceImage = new Image();
referenceImage.src = 'path/to/reference-image.png';

// Wait for both images to load before comparing
sourceImage.onload = () => {
  referenceImage.onload = () => {
    // Set image dimensions
    const sourceWidth = sourceImage.width;
    const sourceHeight = sourceImage.height;
    const referenceWidth = referenceImage.width;
    const referenceHeight = referenceImage.height;

    // Create empty canvas for difference image
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    canvas.width = Math.max(sourceWidth, referenceWidth);
    canvas.height = Math.max(sourceHeight, referenceHeight);

    // Compare images using pixelmatch
    const result = PixelMatcher.match(
      sourceImage.data,
      referenceImage.data,
      sourceWidth,
      sourceHeight,
      referenceWidth,
      referenceHeight,
      { threshold: 0.5 }
    );

    // Draw the difference image on the canvas
    context.putImageData(result.wmv, 0, 0);

    // Log the difference image data (differences per pixel)
    console.log(result.differences);

    // Display the difference image in an element
    document.body.appendChild(canvas);
  };
};
Copied!
Copied!

All versions