🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
现在好多场景都需要改变图片颜色了,比如天气图标,服装换色等,现在有了canvas一切都不是问题了。。。 原理就是通过改变图片的RGBA颜色 ~~~ ctx.getImageData(x,y,width,height); ~~~ ~~~ ctx.putImageData(imgData,x,y,dirtyX,dirtyY,dirtyWidth,dirtyHeight); ~~~ 代码如下: ~~~ var canvas = document.createElement('canvas'); canvas.width = 200; canvas.height = 200; document.body.appendChild(canvas); var ctx = canvas.getContext('2d'); ctx.fillStyle = '#ddd'; ctx.fillRect(0, 0, canvas.width, canvas.height); var img = new Image(); img.src = 'images/1.png'; img.onload = function() { ctx.drawImage(img, 0, 0, img.width, img.height); var imageData = ctx.getImageData(0, 0, img.width, img.height); for(var i=0, len=imageData.data.length; i<len; i+=4) { imageData.data[i] = 255; imageData.data[i+1] = 0; imageData.data[i+2] = 0; imageData.data[i+3] = 100; } ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.putImageData(imageData, 0, 0); } ~~~ 原图: ![](https://box.kancloud.cn/b03fbb29e13e74473357b1f962f7f2a5_213x210.jpg) 改变后: ![](https://box.kancloud.cn/4c4d310d55c1cb1d23d9356dea2b54ec_207x209.jpg) 反色效果: ~~~ var canvas = document.createElement('canvas'); canvas.width = 200; canvas.height = 200; document.body.appendChild(canvas); var ctx = canvas.getContext('2d'); ctx.fillStyle = '#ddd'; ctx.fillRect(0, 0, canvas.width, canvas.height); var img = new Image(); img.src = 'images/1.png'; img.onload = function() { ctx.drawImage(img, 0, 0, img.width, img.height); var imageData = ctx.getImageData(0, 0, img.width, img.height); for(var i=0, len=imageData.data.length; i<len; i+=4) { imageData.data[i] = 255 - imageData.data[i]; imageData.data[i+1] = 255 - imageData.data[i+1]; imageData.data[i+2] = 255 - imageData.data[i+2]; } ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.putImageData(imageData, 0, 0); } ~~~ ![](https://box.kancloud.cn/dc0cefbb7bacf4c14fa13560421450ff_207x211.jpg)