<img src="u398.png" alt="這是個圖片" id="avater"> <script type="text/javascript"> function convertToGS(img){ img.color=img.src; img.grayscale=createGScanvas(img); img.onmouseover=function(){ this.src=this.color; } img.onmouseout=function(){ this.src=this.grayscale; } img.onmouseout(); } function createGScanvas(img){ var canvas=document.createElement("canvas"); canvas.width=img.width; canvas.height-img.height; var ctx=canvas.getContext("2d"); ctx.drawImage(img,0,0); //注意:getImageData只能操做與腳本位於同一個域中的圖片// var c=ctx.getImageData(0,0,img.width,img.height);//將圖片放在服務器中返回給瀏覽器顯示,而後用IE或者firefox瀏覽器瀏覽 for (i = 0; i < c.height; i++) { for ( j = 0; j < c.width; i++) { var x=(i*4)*c.width+(j*4); var r=c.data[x]; var g=c.data[x+1]; var b=c.data[x+2]; c.data[x]=c.data[x+1]=c.data[x+2]=(r+g+b)/3; } } ctx.putImageData(c,0,0,0,0,c.width,c.height); return canvas.toDataURL(); } window.onload=function(){ convertToGS(document.getElementById('avater')); } </script>
咱們在本身本地放圖片加載的時候,本地存儲被默認爲是沒有域可言的,因此在瀏覽器解析的時候就出現了跨域的問題javascript