下面是如何在 JS 中做到这一点。请注意,图像必须来自同一域才能正常工作:
var img = document.getElementById( 'imagebase' );
var canvas = document.getElementById( 'canvasEl' );
// Set Canvas widht and height
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext( '2d' );
ctx.drawImage( img, 0, 0, canvas.width, canvas.height );
// The loop
for ( var x = 0, l = canvas.width; x < l; x++ ) {
for ( var y = 0, lh = canvas.height; y < lh; y++ ) {
// Returns array [Red, Green, Blue, Alpha] each out of 255
var data = ctx.getImageData(x,y,1,1);
// Thresholding: More black than white, and more transparent than not
if ( ( data[0]+data[1]+data[2] ) / 3 < ( 255 / 2 ) && data[3] > 255 / 2 ) {
// Set to black with full opacity
data[0] = 0, data[1] = 0, data[2] = 0, data[3] = 255;
} else {
// Set to transparent
data[3] = 0;
}
ctx.putImageData( data, x, y );
}
}
我使用虚拟 ID 向您展示了工作原理。另外,请查看this page 了解有关像素操作的更多信息。
也就是说,这需要画布才能工作,因此旧版 IE 不支持它(除非您使用 Google 的替换画布,但我不确定它是否支持所有这些方法)。好处是它把负担放在了每个用户身上,而不是所有用户的服务器上。