TwoFace – Canvas based before and after image comparison
Similar to jQuery Before & After plugin, except it has no external dependency. It is drawn onto a Canvas.
HTML
<figure>
<div id="twoface-demo"></div>
<figcaption>Before and after photos of Queensland</figcaption>
</figure>
JavaScript
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 = 0.5;
this.ctx = canvas.getContext('2d');
this.images = [];
// Event handlers
canvas.addEventListener('mousemove', handler, false);
canvas.addEventListener('mousedown', handler, false);
canvas.addEventListener('mouseup', handler, false);
var self = this;
function handler(ev) {
if (ev.layerX || ev.layerX == 0) { // Firefox
ev._x = ev.layerX;
ev._y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
ev._x = ev.offsetX;
ev._y = ev.offsetY;
}
var eventHandler = self[ev.type];
if (typeof eventHandler == 'function') {
eventHandler.call(self, ev);
}
}
// 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) {
if (value > 1) {
value = (value / 100);
}
divide = value;
this.draw();
}
});
}
TwoFace.prototype = {
add: function(src) {
var img = createImage(src, onload.bind(this));
function onload(event) {
this.images.push(img);
if (this.ready) {
...