var my_canvas = document.getElementById('my-canvas');
var context = my_canvas.getContext('2d');
var my_canvas2 = document.createElement('canvas');
var context2 = my_canvas2.getContext('2d');
var w;
var h;
var levels;
var img = new Image();
img.onload = function() {
init();
}
upload_file.addEventListener("change", function() {
uploadFile();
})
function init() {
w = img.width;
h = img.height;
levels = 5;
my_canvas.width = w;
my_canvas.height = h;
my_canvas2.width = w;
my_canvas2.height = h;
context2.drawImage(img,0,0);
main();
hue_slider.onchange = main;
posterize_slider.onchange = main;
}
function main() {
levels = posterize_slider.value;
imgdata = context2.getImageData(0,0,w,h);
imgdata = posterize(imgdata, levels);
context.putImageData(imgdata, 0, 0);
}
function uploadFile(){
var upload = document.getElementById('upload_image'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
upload.src = reader.result;
img.src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
upload.src = "";
}
}
function posterize(imgdata, levels) {
d = imgdata.data;
for(var i=0; i<d.length;i += 4) {
var r = d[i];
var g = d[i+1];
var b = d[i+2];
var avg = (r+g+b) / 3;
var p = (((avg * levels) >> 8) * 255) / (levels - 1);
var lum = p / 255;
var hue = parseInt(hue_slider.value, 10);
var col = hsl2rgb(hue, 1, lum);
d[i] = col.r;
d[i+1] = col.g;
d[i+2] = col.b;
}
imgdata.data = d;
return imgdata;
}
function hsl2rgb(h, s, l) {
var r, g, b, q, p;
h /= 360;
if (s == 0) {
r = g = b = l;
} else...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.