标签:
书籍名称:HTML5-Animation-with-JavaScript
书籍源码:https://github.com/lamberta/html5-animation
1.获取像素数据,改变数据颜色
获取像素是getImageData(startX,startY,endX,endY),
将转换的像素数据绘到画板,采用putImageData(imagedata,posX,posY)传入。
通过注释实例可以更好的理解:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Invert Color</title> <link rel="stylesheet" href="../include/style.css"> </head> <body> <header> Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a> </header> <canvas id="canvas" width="400" height="400"></canvas> <script> window.onload = function () { var canvas = document.getElementById(‘canvas‘), context = canvas.getContext(‘2d‘); //draw some stripes: red, green, and blue for (var i = 0; i < canvas.width; i += 10) { for (var j = 0; j < canvas.height; j += 10) { context.fillStyle = (i % 20 === 0) ? "#f00" : ((i % 30 === 0) ? "#0f0" : "#00f"); context.fillRect(i, j, 10, 10); } } var imagedata = context.getImageData(0, 0, canvas.width, canvas.height), pixels = imagedata.data; //像素数组迭代,每4个表示一个像素的颜色,如pixels[0-1]指的是第一个像素的rgba for (var offset = 0, len = pixels.length; offset < len; offset += 4) { //转化每一个像素颜色数据:rgba(0-255) pixels[offset] = 255 - pixels[offset]; //red to cyan pixels[offset + 1] = 255 - pixels[offset + 1]; //green to magenta pixels[offset + 2] = 255 - pixels[offset + 2]; //blue to yellow //pixels[offset + 4] 透明度(可选元素) } context.putImageData(imagedata, 0, 0); }; </script> </body> </html>
标签:
原文地址:http://www.cnblogs.com/winderby/p/4252832.html