// 返回灰色画布 function grey_img(src,callback){ /*创建一个canvas*/ var canvas=document.createElement('canvas'); var ctx=canvas.getContext('2d'); var img=new Image(); img.src=src; img.onload = function(){ // 因为图片加载时异步的,所以需要采用回调的方式,不然图片宽高读取会变成0导致 Failed to execute 'getImageData' on 'CanvasRenderingContext2D' 报错 canvas.height=img.height; canvas.width=img.width; ctx.drawImage(img,0,0); var imgdata=ctx.getImageData(0,0,canvas.width,canvas.height);var data=imgdata.data; /*灰度处理:求r,g,b的均值,并赋回给r,g,b*/ for(var i=0,n=data.length;i<n;i+=4){ var average=(data[i]+data[i+1]+data[i+2])/3; data[i]=average; data[i+1]=average; data[i+2]=average; } ctx.putImageData(imgdata,0,0); if(typeof callback === 'function'){ /*将处理后的回调给调用者*/ callback({canvas,ctx}); } } } // 灰图变量 var grey_img_icon = null; var Cicon_state = null; // 设置图标函数 function switch_icon(_on_off){ _on_off = !zsl.empty(_on_off); if(Cicon_state !== _on_off){ let path = 'img/icon_128.png'; Cicon_state = _on_off; if(_on_off){ // 恢复正常图标 chrome.browserAction.setIcon({ path }); // 启动程序 // start code…… }else{ if(zsl.empty(grey_img_icon)){ grey_img(path,function(imgObj){ // 设置灰色图标 chrome.browserAction.setIcon({ imageData: imgObj.ctx.getImageData(0,0,128,128) }); }) } // 关闭程序 // close code…… } } }