Skip to content

Instantly share code, notes, and snippets.

@davezen1
Last active May 3, 2018 17:49
Show Gist options
  • Save davezen1/a2849892a342759162702fd3c7a785e7 to your computer and use it in GitHub Desktop.
Save davezen1/a2849892a342759162702fd3c7a785e7 to your computer and use it in GitHub Desktop.
Visual Diff with PhantomJS and Pixelmatch

Testing a website using Visual Diff Image

I got the idea of using a visual diff as part of manual or automated check before pushing to production from Brett Slatkin and https://github.com/bslatkin/dpxdt

This example uses PhantomJs and PixelMatch to generate an image of the running locally and compares it to a baseline image that gives a visual difference so that we can easily spot differences.

PixelMatch is a devDependency while PhantomJs is expected to be installed globally.

  • npm run viz:baseline - creates a new baseline image that uses the public Kitchen Sink page
  • npm run viz:new - creates a new image based on the the local running at http://127.0.0.1:8888
  • npm run viz:check - creates a diff image that highlights the areas where the baseline and new images are different

Typical use after making changes locally:

//example start your local environment
npm run start 
//run the visual diff against the existing baseline image
npm run viz:check
	
//creates a baseline picture of a website
var page = require('webpage').create();
page.open('https://<YOUR SITE>', function () {
page.render('baseline.png');
phantom.exit();
});
// creates a new picture based on a newer version of the target website
// this could be local or test environment
var page = require('webpage').create();
page.open('http://127.0.0.1:8888', function () {
page.render('new.png');
phantom.exit();
});
//snippet of package.json scripts
// dependencies are phantomjs and pixelmatch, typically phantomjs is installed globally
// your setup may vary
"scripts": {
"viz:baseline": "phantomjs baseline.js",
"viz:new": "phantomjs new-viz-diff.js",
"viz:check": "npm run viz:new && node viz-diff.js",
}
// diff the baseline from the new site using pixelmatch
var fs = require('fs'),
PNG = require('pngjs').PNG,
pixelmatch = require('pixelmatch');
var img1 = fs.createReadStream('baseline.png').pipe(new PNG()).on('parsed', doneReading),
img2 = fs.createReadStream('new.png').pipe(new PNG()).on('parsed', doneReading),
filesRead = 0;
function doneReading() {
if (++filesRead < 2) return;
var diff = new PNG({ width: img1.width, height: img1.height });
pixelmatch(img1.data, img2.data, diff.data, img1.width, img1.height, { threshold: 0.1 });
diff.pack().pipe(fs.createWriteStream('diff.png'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment