HTML5 Canvas ( 圖形的像素操做 ) getImageData, putImageData, ImgData.data

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>canvas</title> <script type="text/javascript" src="../js/jQuery.js"></script> <style type="text/css"> *{ margin: 0; padding: 0; outline: none; border: none; } canvas{ width: 4rem; float: left; border: 1px solid black; } canvas:nth-child(2){ float: right; } button{ float: left; padding: .1rem .2rem; font-size: .7rem; } </style> </head> <body> <canvas id="canvasA" width="500" height="400"></canvas> <canvas id="canvasB" width="500" height="400"></canvas> <button id="filter">複製</button> </body> </html> <script type="text/javascript"> /** * rem 佈局初始化 */ $('html').css('font-size', $(window).width()/10); /** * 獲取 canvas 畫布 * 獲取 canvas 繪圖上下文環境 */ var canvasA = $('#canvasA')[0]; var cxtA = canvasA.getContext('2d'); var canvasB = $('#canvasB')[0]; var cxtB = canvasB.getContext('2d'); /** * 獲取canvas畫布的內容 getImageData * 內容放回到canvas畫布 putImageData * 獲取ImgData的每個像素 ImgData.data * getImageData(起始點的橫座標, 起始點的縱座標, 獲取的寬度, 獲取的高度) * putImageData(繪製點的橫座標, 繪製點點縱座標, imgData的起始點橫座標, imgData的起始點縱座標, 寬度, 高度) */ var img = new Image(); img.src = "../img/background_2.jpg"; img.onload = function(){ cxtA.drawImage(img, 0, 0, canvasA.width, canvasA.height); } $('#filter').on('click', function(){ var imgDataA = cxtA.getImageData(0, 0, canvasA.width, canvasA.height); var pxData = imgDataA.data; //獲取每個像素 for(var i = 0; i < canvasB.width * canvasB.height; i++){ //灰度濾鏡 var r = pxData[4*i+0]; var g = pxData[4*i+1]; var b = pxData[4*i+2]; //計算灰度的公式 var grey = 0.3*r + 0.59*g + 0.11*b; pxData[4*i+0] = grey; pxData[4*i+1] = grey; pxData[4*i+2] = grey; } cxtB.putImageData(imgDataA, 0, 0, 0, 0, canvasB.width, canvasB.height); }); </script>
相關文章
相關標籤/搜索