Canvas Pixel Manipulation 像素操作 - caleb531/jcanvas-docs GitHub Wiki

Pixel Manipulation 像素操作

The setPixels() method allows for modification of a specific section of pixels from the canvas.
setPixels()方法允许修改画布上特定区域的像素。
To modify the pixels, you can loop through each pixel using the each callback method.
为了修改像素,你可以在每个像素上循环使用each回调方法。
The each callback function accepts two parameters:
each回调方法接收两个参数:
1.An object containing the properties for red, green, blue, and alpha color values (r, g, b, a)
一个对象,包含了属性redgreenbluealpha颜色,值为(r,g,b,a)
2.The parameters passed to the setPixels() method
传入setPixels()方法的参数

Basic usage 基本用法

function invert() {
  $(this).setPixels({
    x: 150, y: 100,
    width: 220, height: 138,
    // loop through each pixel 循环每个像素
    each: function(px) {
      px.r = 255 - px.r;
      px.g = 255 - px.g;
      px.b = 255 - px.b;
    }
  });
}

$('canvas').drawImage({
  source: 'images/fish.jpg',
  x: 150, y: 100,
  // Invert image color when image loads 当图像调用时,反转图像颜色
  load: invert
});

Pixels and Events 像素及事件

In this example, hovering over the image will manipulate the pixels closest to the part you hovered over.
在本例中,鼠标悬停在图像上,会操纵你所指向区域附近的像素。

function invert(params) {
  $(this).setPixels({
    x: params.eventX, y: params.eventY,
    width: 50, height: 50,
    // loop through each pixel 循环每个像素
    each: function(px) {
      px.r = 255 - px.r;
      px.g = 255 - px.g;
      px.b = 255 - px.b;
    }
  });
}

$('canvas').drawImage({
  layer: true,
  source: 'images/fish.jpg',
  x: 150, y: 100,
  mousemove: invert
});

Notes 注意

If the width, and height properties are not specified, the method loops through every pixel on the canvas.
如果宽高属性没指定,本方法会循环画布上每个像素。
The r, g, b, and a properties all range from 0 to 255.
rgba属性全部被限制在0-255范围内。
As with all jCanvas methods, the setPixels() method respects the value of the fromCenter property, which defaults to true. 就像所有的jCanvas方法那样,setPixels方法遵照fromCenter属性的值,此属性默认为true