0

Let me explain what I want to achieve..

I'm building something just for fun and as a learning experiment similar to

www.milliondollarhomepage.com

Except, I want to use canvas and/or Fabric.js to achieve the same thing. How would I go about manipulating each pixel in a canvas?

Scenario:

  • I want to offer a 1000 pixels up for grabs.
  • User can choose an image and where it should go on the canvas
  • Image can be resized according to how many pixels the user wants and deducted from the overall remaining pixels.

Any help on this would be appreciated!

4

1 回答 1

2

HTML5 canvas api中用于操作单个像素的方法是

context.getImageData(x,y,width,height);

例如

var map = context.getImageData(0,0,canvas.width,canvas.height);

这将返回一个包含重复顺序的大量数组:

[red,green,blue,alpha,red,green,blue,alpha...]

每个4数字代表所选区域上每个像素的红色、绿色、蓝色和 Alpha 通道,从左到右,从上到下。

这些数字中的每一个的值都是一个整数,范围从0 - 255.

循环遍历每个像素并删除它们的redblue通道,从而将图像变为绿色,例如

//assume map variable from earlier

for(var i = 0; i < map.data.length; i+=4){
    map.data[i] = 0; // drop red to 0
    map.data[i+2] = 0; // drop blue to 0
}
context.putImageData(map,0,0);

查看示例

请注意,此过程只能在服务器上完成,并且不会来自其他域的图像“污染”画布。如果不满足这些要求,则会抛出安全错误 DOM 异常。

于 2013-03-09T02:39:57.237 回答