Skip to content

Instantly share code, notes, and snippets.

@philfreo
Created October 10, 2012 04:40
Show Gist options
  • Save philfreo/3863194 to your computer and use it in GitHub Desktop.
Save philfreo/3863194 to your computer and use it in GitHub Desktop.
html5 upload image, pick color, create image
// http://www.solidbg.com/beta/app.js
var file = document.getElementById('file'),
canvas = document.getElementById('canvas'),
preview = document.getElementById('preview'),
ctx = canvas.getContext('2d'),
ua = navigator.userAgent.toLowerCase(),
isMobileSafari = (ua.indexOf('mobile') > -1 && ua.indexOf('safari') > -1);
file.onchange = readFile;
canvas.onmousemove = getPixel;
canvas.ontouchstart = getPixel;
canvas.ontouchmove = getPixel;
preview.onclick = goToColor;
preview.ontouchend = goToColor;
function goToColor() {
var color = preview.style.backgroundColor,
colorCanvas = document.createElement('canvas'),
colorCtx = colorCanvas.getContext('2d');
colorCanvas.width = screen.width;
colorCanvas.height = screen.height;
colorCtx.fillStyle = color;
colorCtx.beginPath();
colorCtx.rect (0, 0, colorCanvas.width, colorCanvas.height);
colorCtx.fill();
window.location = colorCanvas.toDataURL('image/png');
}
function readFile() {
var reader = new FileReader();
reader.onload = loadImage;
reader.readAsDataURL(this.files[0]);
preview.style.display = '';
}
function loadImage(e) {
var img = new Image();
img.onload = drawImage;
img.src = e.target.result;
}
function drawImage() {
var imgw = this.width,
imgh = this.height,
isWide = imgw > imgh,
r = Math.min(imgw, imgh) / Math.max(imgw, imgh),
cw = Math.min(imgw, 300),
ch = isWide ? cw * r : cw * (1 - (r - 1));
canvas.width = cw;
canvas.height = ch;
ctx.drawImage(this, 0, 0, imgw, imgh, 0, 0, cw, isMobileSafari ? ch * 4 : ch);
}
function getPixel(e) {
var x = e.offsetX || e.touches[0].clientX - this.offsetLeft,
y = e.offsetY || e.touches[0].clientY - this.offsetTop,
pixel = ctx.getImageData(x, y, 1, 1).data;
preview.style.backgroundColor = 'rgb(' + pixel[0] + ',' + pixel[1] + ',' + pixel[2] + ')';
e.preventDefault();
e.stopPropagation();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment