JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
console.clear();
function each(obj, callback) {
var length = obj.length,
likeArray = (length === 0 || (length > 0 && (length - 1) in obj)),
i = 0;
if (likeArray) {
for (; i < length; i++) {
if (callback.call(obj[i], i, obj[i]) === false) {
break;
}
}
} else {
for (i in obj) {
if (callback.call(obj[i], i, obj[i]) === false) {
break;
}
}
}
}
function byteCount(s) {
return encodeURI(s).split(/%..|./).length - 1;
}
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function getColor(r, g, b, a) {
if (a === undefined || a === 255) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
if (a === 0) {
return false;
}
return 'rgba(' + r + ',' + g + ',' + b + ',' + (a / 255) + ')';
}
// Optimized for horizontal lines
function makePathData(x, y, w) {
return ('M' + x + ' ' + y + 'h' + w + '');
}
function path(color, data) {
return '\n';
}
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var uploader = document.getElementById('upload');
var outputDiv = document.getElementById('output');
var outputRaw = document.getElementById('outputRaw');
function processImage(src) {
var img = new Image();
img.onload = function() {
var width = img.width;
var height = img.height;
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0);
// viewBox starts at -0.5 to accomodate stroke's middle-origin to prevent having to include 0.5 on each path move
var output = '\n';
var colors = {},
x = 0,
y = 0,
p, color;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
p = ctx.getImageData(x, y, 1, 1).data;
color = getColor(p[0], p[1], p[2], p[3]);
if (color) {
colors[color] = colors[color] || [];
colors[color].push([x, y]);
}
}
}
// Loop through each color
each(colors, function(i, value) {
if (i === false) {
return;
}
var paths = [];
var curPath;
var w = 1;
// Loops through each color's pixels to optimize paths
each(value, function() {
if (curPath && this[1] === curPath[1] && this[0] === (curPath[0] + w)) {
w++;
} else {
if (curPath) {
paths.push(makePathData(curPath[0], curPath[1], w));
w = 1;
}
curPath = this;
}
});
paths.push(makePathData(curPath[0], curPath[1], w)); // Finish last path
output += path(i, paths.join(''));
});
output += '';
outputDiv.innerHTML = 'Output size (bytes): ' + byteCount(output) + '' + 'Download SVG' + output + '';
outputRaw.innerHTML = output.replace(//g, '>');
}
img.src = (src.target ? src.target.result : src);
}
function loadImage(e) {
var reader = new FileReader();
reader.onload = processImage;
file = (e.target.files || uploader.files)[0];
if (file) {
reader.readAsDataURL(file);
}
}
uploader.onclick = uploader.onchange = loadImage;
var test = document.getElementById('test');
var testImage = document.getElementById('testImage');
test.onclick = function() {
processImage(testImage.src);
}