-
-
Save oguzhanaslan/2d4d5575af3cc8eed61a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(global) { | |
function Dither(container, width, height) { | |
this.container = container; | |
this.width = width; | |
this.height = height; | |
this.canvas = null; | |
this.image = null; | |
this.draw = this.draw.bind(this); | |
this.handleSliderChange = this.handleSliderChange.bind(this); | |
this.handleDragOver = this.handleDragOver.bind(this); | |
this.handleDrop = this.handleDrop.bind(this); | |
} | |
Dither.prototype.init = function() { | |
this.canvas = this.container.ownerDocument.createElement('canvas'); | |
this.canvas.width = this.width; | |
this.canvas.height = this.height; | |
this.canvas.addEventListener('dragover', this.handleDragOver, true); | |
this.canvas.addEventListener('drop', this.handleDrop, true); | |
this.canvas.style.outline = '1px outset #ccc'; | |
this.slider = this.container.ownerDocument.createElement('input'); | |
this.slider.type = 'range'; | |
this.slider.min = 2; | |
this.slider.max = 16; | |
this.slider.value = 2; | |
this.slider.addEventListener('change', this.handleSliderChange); | |
this.container.appendChild(this.canvas); | |
this.container.appendChild(this.slider); | |
}; | |
Dither.prototype.loadImage = function(file) { | |
this.image = new Image; | |
this.image.src = URL.createObjectURL(file); | |
this.image.onload = this.draw; | |
} | |
Dither.prototype.draw = function() { | |
var ctx = this.canvas.getContext('2d'); | |
ctx.drawImage(this.image, 0, 0, this.width, this.height); | |
var pixels = ctx.getImageData(0, 0, this.width, this.height); | |
for (var j = 0; j < this.height - 1; j++) { | |
for (var i = 0; i < this.width - 1; i++) { | |
var idx = 4 * (j * this.height + i), | |
r = pixels[idx], | |
g = pixels[idx+1], | |
b = pixels[idx+2], | |
l = this.constructor.luma(r, g, b), | |
v = Math.round(Math.round((l / 255) * this.slider.value) / this.slider.value * 255); | |
pixels[idx] = pixels[idx + 1] = pixels[idx + 2] = v; | |
} | |
} | |
ctx.putImageData(pixels, 0, 0); | |
}; | |
Dither.prototype.handleSliderChange = function(ev) { | |
this.draw(); | |
}; | |
Dither.prototype.handleDragOver = function(ev) { | |
ev.preventDefault(); | |
}; | |
Dither.prototype.handleDrop = function(ev){ | |
ev.preventDefault(); | |
this.loadImage(ev.dataTransfer.files[0]); | |
}; | |
Dither.luma = function(r, g, b) { | |
return Math.round(0.2126 * r + 0.7152 * g + 0.0722 * b); | |
}; | |
global.Dither = Dither; | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment