Skip to content

Instantly share code, notes, and snippets.

@hongymagic
Created April 17, 2012 04:52
Show Gist options
  • Save hongymagic/2403518 to your computer and use it in GitHub Desktop.
Save hongymagic/2403518 to your computer and use it in GitHub Desktop.
TwoFace – Canvas based Image before/after comparison
function TwoFace(id, width, height) {
if (!(this instanceof TwoFace)) {
return new TwoFace(id, width, height);
}
var canvas = document.createElement('canvas'),
container = document.getElementById(id),
divide = 50;
this.ctx = canvas.getContext('2d');
this.images = [];
// Draw canvas into its container
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
container.appendChild(canvas);
Object.defineProperty(this, 'ready', {
get: function() {
return this.images.length >= 2;
}
});
Object.defineProperty(this, 'width', {
get: function() {
return width;
}
});
Object.defineProperty(this, 'height', {
get: function() {
return height;
}
});
Object.defineProperty(this, 'divide', {
get: function() {
return divide;
},
set: function(value) {
divide = value;
this.draw();
}
});
}
TwoFace.prototype = {
add: function(src) {
this.images.push(createImage(src));
if (this.ready) {
this.draw();
}
},
draw: function() {
if (!this.ready) {
return;
}
var lastIndex = this.images.length - 1,
before = this.images[lastIndex - 1],
after = this.images[lastIndex],
split = (this.divide / 100) * this.width,
lx = 0,
ly = 0,
lw = split,
lh = this.height,
rx = 0,
ry = 0,
rw = this.width,
rh = this.height;
drawImages(this.ctx);
drawHandle(this.ctx);
function drawImages(ctx) {
ctx.drawImage(after, rx, ry);
ctx.drawImage(before, lx, ly, lw, lh, 0, 0, lw, lh);
}
function drawHandle(ctx) {
ctx.fillStyle = "rgb(220, 50, 50)";
ctx.fillRect(split - 1, 0, 2, rh);
}
}
}
function createImage(src) {
var img = document.createElement('img');
img.src = src;
return img;
}
var twoface = TwoFace('twoface-demo', 320, 240);
twoface.add('http://placehold.it/320x240/000000/ffffff');
twoface.add('http://placehold.it/320x240/ffffff/000000');
function changeDivide() {
var divide = (document.getElementById('twoface-controller').value * 1.0).toFixed(2);
twoface.divide = divide;
}
@lionel-
Copy link

lionel- commented Apr 14, 2016

Hello @hongymagic

Would you be ok to licence this code as open source? More precisely the jsfiddle version, not the earlier version in this gist. I'd like to use it in my R package https://github.com/lionel-/vdiffr

E.g. https://github.com/lionel-/vdiffr/blob/master/inst/htmlwidgets/lib/twoface.js

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment