在您的演示代码中,您应该更改临时画布宽度/高度,而不是上下文。
helperCanvas.width = image.width;
helperCanvas.height = image.height;
这是带有测试过滤器的代码,它只会将所有非透明像素变为红色。
它还将过滤后的画布图像呈现为页面上的图像。
顺便说一句,在创建图像对象时,如果您这样创建,可以避免一个新的 Chrome 错误:
var img=document.createElement("img");
必须在 Chrome 或 FF 中查看的小提琴(IE==CORS 失败):http: //jsfiddle.net/m1erickson/LeGD5/
这是代码:
<!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.createElement("canvas");
var ctx=canvas.getContext("2d");
var img=document.createElement("img");
img.onload=function(){
canvas.width=img.width;
canvas.height=img.height;
ctx.drawImage(img,0,0,img.width,img.height);
// test -- turn every non-transparent pixel red
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var pixels = imgData.data; // get pixel data
for (var i = 0; i < pixels.length; i +=4)
{
// if this pixel is not transparent,
// mask it in pure red
if(pixels[i+3]>0){
pixels[i]=255; // this is the red component of the pixel
pixels[i+1]=0; // this is the green component of the pixel
pixels[i+2]=0; // this is the blue component of the pixel
pixels[i+3]=255; // this is the alpha component of the pixel
}
}
ctx.putImageData(imgData, 0, 0);
var theImage=document.getElementById("theImage");
theImage.src=canvas.toDataURL();
}
img.crossOrigin="anonymous";
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/KoolAidMan.png";
}); // end $(function(){});
</script>
</head>
<body>
<img id="theImage" width=300 height=300>
</body>
</html>