您可以一次创建每种所需的颜色,然后将其存储为图像以供重复使用。
// create an image from the canvas and push the image into an array for reuse
var img=new Image();
img.src=canvas.toDataURL();
myColoredImages.push(img);
您可以使用 source-in 合成操作重新着色图像:
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();
}
这是必须在 Chrome 或 FF 中查看的小提琴(CORS 问题):http: //jsfiddle.net/m1erickson/Yqg2Y/
这是代码:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var canvas2 = document.getElementById('canvas2');
var ctx2 = canvas2.getContext('2d');
var colors=[];
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();
return(img);
}
function loadColor(n){
ctx2.clearRect(0,0,canvas2.width,canvas2.height);
ctx2.drawImage(colors[n],0,0);
}
$("#red").click(function(){ loadColor(0); });
$("#green").click(function(){ loadColor(1); });
$("#blue").click(function(){ loadColor(2); });
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=200 height=200></canvas>
<canvas id="canvas2" width=200 height=200></canvas><br>
<button id="red">Red</button>
<button id="green">Green</button>
<button id="blue">Blue</button>
</body>
</html>