您遇到跨域安全违规(CORS 违规)。
也许最简单的解决方法是将图像托管在允许匿名下载图像的站点上。然后不会触发 CORS 错误,并且您的颜色选择器可以工作。
Dropbox.com 就是这样一个网站。
您需要进行的唯一应用更改是将图像的 crossOrigin 标志设置为匿名。
// create a new image object
var img=new Image();
// set its crossOrigin flag to anonymous
// to allow downloading from dropbox.com (or any X-domain enabled site)
img.crossOrigin="anonymous";
这是完整的代码和小提琴:http: //jsfiddle.net/m1erickson/y2P79/
<!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; padding:20px;}
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var img=new Image();
img.onload=function(){
canvas.width=img.width;
canvas.height=img.height;
ctx.drawImage(img,0,0);
}
img.crossOrigin="anonymous";
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/colorhouse.png";
$("#canvas").click(function(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// desaturation colors
var imgData=ctx.getImageData(mouseX,mouseY,1,1);
var data=imgData.data;
$("#results").text("Color at "+mouseX+"/"+mouseY+" is rgba("
+data[0]+","+data[1]+","+data[2]+","+data[3]+")");
});
}); // end $(function(){});
</script>
</head>
<body>
<p id="results">Click to get color</p>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>