JSFiddle - React, Tailwind, and code Playground
globalCompositeOperation svg image coloring javascript JQuery UI
by Andrew Pougher
HTML
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css">
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<div style="display:inline-block;border: 1px solid;position:absolute">
<img src="" class="icn" style="width:100%">
</div>
<canvas id="canvas" width=200 height=200 style="display:none"></canvas>
<br>
<button id="red" class="btn btn-xs btn-default">red</button>
<button id="beige" class="btn btn-xs btn-default">Beige</button>
<button id="orange" class="btn btn-xs btn-default">orange</button>
<button id="blue" class="btn btn-xs btn-default">Blue</button>
CSS
body {
background-color: white;
height:100vh
}
canvas {
border:1px solid red;
}
JavaScript
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var pic = new Image();
pic.onload = function () {
canvas.width = pic.width;
canvas.height = pic.height;
canvas2.width = pic.width;
canvas2.height = pic.height;
ctx.drawImage(pic, 0, 0);
colors.push(recolor("red"));
colors.push(recolor("green"));
colors.push(recolor("blue"));
}
pic.crossOrigin = "anonymous";
pic.src = 'https://dl.dropboxusercontent.com/u/139992952/stackoverflow/temp.png';
function recolor(color) {
ctx.save();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(pic, 0, 0);
ctx.globalCompositeOperation = "source-in";
ctx.fillStyle = color;
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fill();
ctx.restore();
var img = new Image();
img.src = canvas.toDataURL();
$(".icn").attr("src", img.src).parent().draggable({
//snap: false,
containment: "body",
stack: ".topme",
opacity: .55,
scroll: false,
start: function(event, ui) {},
stop: function(event, ui) {}
}).resizable({
aspectRatio: true,
autoHide: true,
alsoResize: $(this).find('img')
});
return (img);
}
$("#red").click(function () {
recolor("#cc1100");
});
$("#beige").click(function () {
recolor("#ececdd");
});
$("#orange").click(function () {
recolor("orange");
});
$("#blue").click(function () {
recolor("#9387cd");
});
// first trigger
$("button#red").click();
...