1 var oImg = new Image(); 2 oImg.src = './img/mv.jpg'; 3 oImg.onload = function () { 4 oGc.drawImage(oImg, 10, 10); 5 var imgData = oGc.getImageData(10, 10, 200, 200), 6 data = imgData.data, avg = 0; 7 for( var i = 0; i < data.length; i += 4 ) { 8 avg = ( data[i] + data[i+1] + data[i+2] / 3 ); 9 data[i] = 0; 10 data[i+1] = 0; 11 data[i+2] = avg; 12 } oGc.putImageData( imgData, 220, 10 ); 15 }
六、透明度
这个很简单,只要把透明度乘以一个0~1之间的值即可。跟css的opacity一样
1 var oImg = new Image(); 2 oImg.src = './img/mv.jpg'; 3 oImg.onload = function () { 4 oGc.drawImage(oImg, 10, 10); 5 var imgData = oGc.getImageData(10, 10, 200, 200), 6 data = imgData.data, avg = 0; 7 for( var i = 0; i < data.length; i += 4 ) { 8 data[i+3] *= 0.2; 9 } oGc.putImageData( imgData, 220, 10 ); 12 }
七、createImageData:根据图片或者某个宽度与高度创建一个像素区域
cxt.createImageData( w, h )
cxt.createImageData( imgData )
w, h:创建区域的宽度与高度
imgData: 创建的区域与这个像素区域的宽度和高度相同,imgData就是通过getImageData获取到图片像素的 返回值
1,根据一个图片的宽度与高度,创建一个透明的红色像素区域
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset='utf-8' /> 5 <style> 6 #canvas { 7 border: 1px dashed #aaa; 8 } 9 </style> 10 <script> 11 window.onload = function () { 12 var oCanvas = document.querySelector("#canvas"), 13 oGc = oCanvas.getContext('2d'); oImg = new Image(); 16 oImg.src = './img/mv.jpg'; 17 oImg.onload = function () { 18 oGc.drawImage(oImg, 10, 10); 19 var imgData = oGc.getImageData(10, 10, 200, 200), 20 data = imgData.data, 21 imgData2 = oGc.createImageData( imgData ), 22 data2 = imgData2.data; 23 for( var i = 0; i < imgData2.width * imgData2.height * 4; i += 4 ) { 24 data2[i] = 255; 25 data2[i+1] = 0; 26 data2[i+2] = 0; 27 data2[i+3] = 30; 28 } oGc.putImageData( imgData2, 220, 10 ); 31 } 32 } 33 </script> 34 </head> 35 <body> 36 <canvas></canvas> 37 </body> 38 </html>
2,自定一个200 x 200的蓝色透明像素区域
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset='utf-8' /> 5 <style> 6 #canvas { 7 border: 1px dashed #aaa; 8 } 9 </style> 10 <script> 11 window.onload = function () { 12 var oCanvas = document.querySelector("#canvas"), 13 oGc = oCanvas.getContext('2d'); imgData = oGc.createImageData( 200, 200 ), 16 data = imgData.data; 17 for( var i = 0; i < imgData.width * imgData.height * 4 ; i += 4 ){ 18 data[i] = 0; 19 data[i+1] = 0; 20 data[i+2] = 255; 21 data[i+3] = 100; 22 } 23 oGc.putImageData( imgData, 10, 10 ); 24 } 25 </script> 26 </head> 27 <body> 28 <canvas></canvas> 29 </body> 30 </html>