JSFiddle - React, Tailwind, and code Playground
by jesse1983
HTML
<div ng-app="color-replace">
<h1>
Original
</h1>
<img src="https://raw.githubusercontent.com/jesse1983/angular-image-color-replacement/master/image.png" />
<h1>
Replacement
</h1>
<img src="https://raw.githubusercontent.com/jesse1983/angular-image-color-replacement/master/image.png" color-replace="[{from: '#FF0000', to:'#FFFF00'},{from: '#00FF00', to:'#00A4FF', tolerance: 50}]" />
</div>
JavaScript
var ImageReplacer, ImageReplacerDirective;
ImageReplacer = (function() {
var context2d, drawImage, imageToCanvas, isnear, proximity, rgbToHex;
ImageReplacer.original = null;
ImageReplacer.canvas = null;
function ImageReplacer(image) {
this.original = image;
this.canvas = imageToCanvas(image);
this.ctx = context2d(this.canvas);
this.drawed = drawImage(this.ctx, image);
}
rgbToHex = function(RGB) {
var arr, i, j, len, ref;
RGB = RGB.replace("#", "");
arr = [];
if (RGB.length === 6) {
ref = [0, 1, 2];
for (j = 0, len = ref.length; j < len; j++) {
i = ref[j];
arr.push(parseInt(RGB.substr(i * 2, 2), 16));
}
}
return arr;
};
imageToCanvas = function(image) {
var c;
c = document.createElement('canvas');
c.width = image.width;
c.height = image.height;
return c;
};
context2d = function(canvas) {
if (canvas) {
return canvas.getContext("2d");
}
};
drawImage = function(ctx, image) {
var imageData;
ctx.drawImage(image, 0, 0, image.width, image.height);
imageData = ctx.getImageData(0, 0, image.width, image.height);
return imageData;
};
proximity = function(n1, n2) {
return Math.abs(n1 - n2);
};
isnear = function(n1, n2, tolerance) {
if (n1 > n2) {
return n1 < (n2 + tolerance);
} else {
return n1 > (n2 - tolerance);
}
};
ImageReplacer.prototype.replaceColors = function(objReplace) {
var from, i, j, len, r, to;
if (objReplace) {
if (objReplace.length > 0) {
i = 0;
while (i < this.drawed.data.length) {
for (j = 0, len = objReplace.length; j < len; j++) {
r = objReplace[j];
from = rgbToHex(r.from);
to = rgbToHex(r.to);
if (!r.tolerance) {
r.tolerance = 10;
}
if (proximity(this.drawed.data[i + 0], from[0]) <= r.tolerance && proximity(this.drawed.data[i + 1],...