标签:环境 pad context charset html5 html 上下 内容 宽度
<!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>
HTML5 Canvas ( 图形的像素操作 ) getImageData, putImageData, ImgData.data
标签:环境 pad context charset html5 html 上下 内容 宽度
原文地址:http://www.cnblogs.com/lovling/p/6683418.html