首页  >  文章  >  web前端  >  canvas的ImageData怎么使用

canvas的ImageData怎么使用

php中世界最好的语言
php中世界最好的语言原创
2018-05-15 14:24:562030浏览


在我们之前有很多关于canvas的文章,大家感兴趣的可以看一下,其中有一篇是关于canvas绘制video,其实canvas的功能还有许多,今天就来介绍一下camvas的ImageDate对象的应用。

canvas的ImageData 对象

ImageData对象中存储着canvas对象真实的像素数据,它包含以下几个只读属性:

width

图片宽度,单位是像素

height

图片高度,单位是像素

data

Uint8ClampedArray类型的一维数组,包含着RGBA格式的整型数据,范围在0至255之间(包括255)。

创建一个ImageData对象

去创建一个新的,空白的ImageData对象,你应该会使用createImageData() 方法。

var myImageData = ctx.createImageData(width, height);

上面代码创建了一个新的具体特定尺寸的ImageData对象。所有像素被预设为透明黑。

得到场景像素数据

为了获得一个包含画布场景像素数据的ImageData对像,你可以用getImageData()方法:

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

这个方法会返回一个ImageData对象,它代表了画布区域的对象数据,此画布的四个角落分别表示为(left, top), (left + width, top), (left, top + height), 以及(left + width, top + height)四个点。这些坐标点被设定为画布坐标空间元素。

在场景中写入像素数据

你可以用putImageData()方法去对场景进行像素数据的写入。

ctx.putImageData(myImageData, dx, dy);

dx和dy参数表示你希望在场景内左上角绘制的像素数据所得到的设备坐标。

例如,为了在场景内左上角绘制myImageData代表的图片,你可以写如下的代码:

ctx.putImageData(myImageData, 0, 0);
toDataURL 将canvas转为 data URI格式


有如下7272dcc38f587c12b78cbd2de8ee8ef4元素

<canvas id="canvas" width="5" height="5"></canvas>
var canvas = document.getElementById("canvas");
var dataURL = canvas.toDataURL();
console.log(dataURL);
// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"
var fullQuality = canvas.toDataURL("image/jpeg", 1.0);
// data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...9oADAMBAAIRAxEAPwD/AD/6AP/Z"
var mediumQuality = canvas.toDataURL("image/jpeg", 0.5);
var lowQuality = canvas.toDataURL("image/jpeg", 0.1);
应用一:颜色选择器
var img = new Image();
img.src = &#39;haorooms.jpg&#39;;
var canvas = document.getElementById(&#39;canvas&#39;);
var ctx = canvas.getContext(&#39;2d&#39;);
img.onload = function() {
  ctx.drawImage(img, 0, 0);
  img.style.display = &#39;none&#39;;
};
var color = document.getElementById(&#39;color&#39;);
function pick(event) {
  var x = event.layerX;
  var y = event.layerY;
  var pixel = ctx.getImageData(x, y, 1, 1);
  var data = pixel.data;
  console.log(data);
  var rgba = &#39;rgba(&#39; + data[0] + &#39;,&#39; + data[1] +
             &#39;,&#39; + data[2] + &#39;,&#39; + (data[3] / 255) + &#39;)&#39;;
  color.style.background =  rgba;
  color.textContent = rgba;
}
canvas.addEventListener(&#39;mousemove&#39;, pick);

应用二:视频纯色背景过滤

 今天,我们用getImageData过滤掉纯色背景。

let processor = {
  timerCallback: function() {
    if (this.video.paused || this.video.ended) {
      return;
    }
    this.computeFrame();
    let self = this;
    setTimeout(function () {
        self.timerCallback();
      }, 0);
  },
  doLoad: function() {
    this.video = document.getElementById("video");
    this.c1 = document.getElementById("c1");
    this.ctx1 = this.c1.getContext("2d");
    this.c2 = document.getElementById("c2");
    this.ctx2 = this.c2.getContext("2d");
    let self = this;
    this.video.addEventListener("play", function() {
        self.width = self.video.videoWidth / 2;
        self.height = self.video.videoHeight / 2;
        self.timerCallback();
      }, false);
  },
  computeFrame: function() {
    this.ctx1.drawImage(this.video, 0, 0, this.width, this.height);
    let frame = this.ctx1.getImageData(0, 0, this.width, this.height);
        let l = frame.data.length / 4;
    for (let i = 0; i < l; i++) {
      let r = frame.data[i * 4 + 0];
      let g = frame.data[i * 4 + 1];
      let b = frame.data[i * 4 + 2];
      if (g > 100 && r > 100 && b < 43)
        frame.data[i * 4 + 3] = 0;
    }
    this.ctx2.putImageData(frame, 0, 0);
    return;
  }
};

应用三:图片灰度和反相颜色

在这个例子里,我们遍历所有像素以改变他们的数值。然后我们将被修改的像素数组通过putImageData()放回到画布中去。invert函数仅仅是去减掉颜色的最大色值255.grayscale函数仅仅是用红绿和蓝的平均值。你也可以用加权平均,例如x = 0.299r + 0.587g + 0.114b这个公式。

var img = new Image();
img.src = &#39;rhino.jpg&#39;;
img.onload = function() {
  draw(this);
};
function draw(img) {
  var canvas = document.getElementById(&#39;canvas&#39;);
  var ctx = canvas.getContext(&#39;2d&#39;);
  ctx.drawImage(img, 0, 0);
  img.style.display = &#39;none&#39;;
  var imageData = ctx.getImageData(0,0,canvas.width, canvas.height);
  var data = imageData.data;
  var invert = function() {
    for (var i = 0; i < data.length; i += 4) {
      data[i]     = 225 - data[i];     // red
      data[i + 1] = 225 - data[i + 1]; // green
      data[i + 2] = 225 - data[i + 2]; // blue
    }
    ctx.putImageData(imageData, 0, 0);
  };
  var grayscale = function() {
    for (var i = 0; i < data.length; i += 4) {
      var avg = (data[i] + data[i +1] + data[i +2]) / 3;
      data[i]     = avg; // red
      data[i + 1] = avg; // green
      data[i + 2] = avg; // blue
    }
    ctx.putImageData(imageData, 0, 0);
  };
  var invertbtn = document.getElementById(&#39;invertbtn&#39;);
  invertbtn.addEventListener(&#39;click&#39;, invert);
  var grayscalebtn = document.getElementById(&#39;grayscalebtn&#39;);
  grayscalebtn.addEventListener(&#39;click&#39;, grayscale);
}


应用四-缩放和反锯齿

var img = new Image();
img.src = &#39;haorooms.jpg&#39;;
img.onload = function() {
  draw(this);
};
function draw(img) {
  var canvas = document.getElementById(&#39;canvas&#39;);
  var ctx = canvas.getContext(&#39;2d&#39;);
  ctx.drawImage(img, 0, 0);
  img.style.display = &#39;none&#39;;
  var zoomctx = document.getElementById(&#39;zoom&#39;).getContext(&#39;2d&#39;);
  var smoothbtn = document.getElementById(&#39;smoothbtn&#39;);
  var toggleSmoothing = function(event) {
    zoomctx.imageSmoothingEnabled = this.checked;
    zoomctx.mozImageSmoothingEnabled = this.checked;
    zoomctx.webkitImageSmoothingEnabled = this.checked;
    zoomctx.msImageSmoothingEnabled = this.checked;
  };
  smoothbtn.addEventListener(&#39;change&#39;, toggleSmoothing);
  var zoom = function(event) {
    var x = event.layerX;
    var y = event.layerY;
    zoomctx.drawImage(canvas,
                      Math.abs(x - 5),
                      Math.abs(y - 5),
                      10, 10,
                      0, 0,
                      200, 200);
  };
  canvas.addEventListener(&#39;mousemove&#39;, zoom);
}

应用五-canvas手绘并下载图片

window.addEventListener(&#39;load&#39;, function(ev) {
    var sourceimage = document.querySelector(&#39;img&#39;);
    var canvas = document.querySelector(&#39;canvas&#39;);
    var link = document.querySelector(&#39;a&#39;);
    var context = canvas.getContext(&#39;2d&#39;);
    var mouseX = 0, mouseY = 0,
        width = 300, height = 300,
        mousedown = false;
    canvas.width = width;
    canvas.height = height;
    context.fillStyle = &#39;hotpink&#39;; 
    function draw(ev) {
      if (mousedown) {
        var x = ev.layerX;
        var y = ev.layerY;
        x = (Math.ceil(x / 10) * 10) - 10;
        y = (Math.ceil(y / 5) * 5) - 5;
        context.fillRect(x, y, 10, 5);
      }
    }
    var link = document.createElement(&#39;a&#39;);
        link.innerHTML = &#39;下载图片&#39;;
        link.href = "#";
        link.download = "haorooms.png";
    document.body.insertBefore(link, canvas);
    canvas.addEventListener(&#39;mouseover&#39;, function(ev) {
      document.body.classList.add(&#39;painted&#39;);
    }, false);
    canvas.addEventListener(&#39;mousemove&#39;, draw, false);
    canvas.addEventListener(&#39;mousedown&#39;, function(ev) {
      mousedown = true;
    }, false );
    canvas.addEventListener(&#39;mouseup&#39;, function(ev) {
      link.href = canvas.toDataURL();
      mousedown = false;
    }, false );
  } ,false);

相信看了这些案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!


相关阅读:

CSS3的loading特效怎么制作

怎样用css3做出图标效果

CSS的编码怎么转换

以上是canvas的ImageData怎么使用的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn