4.canvas ImageData对象

2019-04-11  本文已影响0人  琉璃_xin

1.创建一个ImageData对象

2.得到场景像素数据

var myImageData = ctx.getImageData(left, top, width, height);

  let canvas = document.getElementById('canvas');
  let ctx = canvas.getContext('2d');
  let sun = new Image();
  sun.onload = function () {
    ctx.drawImage(sun,0,0);
    //imageData
    let imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
    console.log(imageData)

  }
  sun.src = './Canvas_sun.png';
image.png
data属性返回一个 Uint8ClampedArray,它可以被使用作为查看初始像素数据。每个像素用4个1bytes值(按照红,绿,蓝和透明值的顺序; 这就是"RGBA"格式) 来代表。每个颜色值部份用0至255来代表。每个部份被分配到一个在数组内连续的索引,左上角像素的红色部份在数组的索引0位置。像素从左到右被处理,然后往下,遍历整个数组。

如何通过具体位置信息读取其像素值呢?
(200,50) 位置处的蓝色像素信息:
let blue = imageData.data[((50-1)*imageData.width + (200-1))*4 - 1 + 3];
根据行、列读取某像素点的R/G/B/A值的公式:
imageData.data[((行数-1)*imageData.width + (列数-1))*4 - 1 + 1/2/3/4];

  let img = new Image();
  img.src = './rhino.jpg';
  let canvas = document.getElementById('canvas');
  let ctx = canvas.getContext('2d');
  img.onload = function() {
    ctx.drawImage(img, 0, 0);
    img.style.display = 'none';
  };
  let color = document.getElementById('color');
  function pick(event) {
    let x = event.layerX;
    let y = event.layerY;
    let pixel = ctx.getImageData(x, y, 1, 1);
    let data = pixel.data;
    console.log(data)
    let rgba = 'rgba(' + data[0] + ',' + data[1] +
              ',' + data[2] + ',' + (data[3] / 255) + ')';
    color.style.background =  rgba;
    color.textContent = rgba;
  }
  canvas.addEventListener('mousemove', pick);
image.png

3.写入像素数据

ctx.putImageData(myImageData, dx, dy);
dx和dy参数表示你希望在场景内左上角绘制的像素数据所得到的设备坐标

  let canvas = document.getElementById('canvas');
  let ctx = canvas.getContext('2d');
  let sun = new Image();
  sun.onload = function () {
    ctx.drawImage(sun,0,0);
    //imageData
    let imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
    
    //putImageData
    ctx.putImageData(imageData,200,200)

  }
  sun.src = './Canvas_sun.png';
image.png

可以将数据操作后再放入场景(将上述图形色值取反):

  let canvas = document.getElementById('canvas');
  let ctx = canvas.getContext('2d');
  let sun = new Image();
  sun.onload = function () {
    ctx.drawImage(sun,0,0);
    //imageData
    let imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
    
    for (let i = 0;i < imageData.data.length; i += 4){
      imageData.data[i]     = 255 - imageData.data[i];     // red
      imageData.data[i + 1] = 255 - imageData.data[i + 1]; // green
      imageData.data[i + 2] = 255 - imageData.data[i + 2]; // blue
    }
    //putImageData
    ctx.putImageData(imageData,200,200)

  }
  sun.src = './Canvas_sun.png';
image.png

4.保存为图片

canvas.toDataURL()

上一篇下一篇

猜你喜欢

热点阅读