Home > Web Front-end > HTML Tutorial > How to use ImageData of canvas

How to use ImageData of canvas

php中世界最好的语言
Release: 2018-05-15 14:24:56
Original
2080 people have browsed it


We have had many articles about canvas before. If you are interested, you can take a look. One of them is about canvas drawing video. In fact, canvas has many functions. Let’s take a look today. Introducing the application of the ImageDate object of camvas.

ImageData object of canvas

The ImageData object stores the real pixel data of the canvas object. It contains the following read-only attributes:

width

Picture width, unit is pixels

height

Picture height, unit is pixels

data

Uint8ClampedArray type One-dimensional array contains integer data in RGBA format, ranging from 0 to 255 (inclusive of 255).

Create an ImageData object

To create a new, blank ImageData object, you should use the createImageData() method.

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

The above code creates a new ImageData object of a specific size. All pixels are preset to transparent black.

Get scene pixel data

In order to obtain an ImageData object containing canvas scene pixel data, you can use the getImageData() method:

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

This method will return an ImageData Object, which represents the object data of the canvas area. The four corners of the canvas are represented as (left, top), (left + width, top), (left, top + height), and (left + width, top + height) four points. These coordinate points are set as canvas coordinate space elements.

Write pixel data into the scene

You can use the putImageData() method to write pixel data into the scene.

ctx.putImageData(myImageData, dx, dy);
Copy after login

The dx and dy parameters represent the device coordinates obtained from the pixel data you want to draw in the upper left corner of the scene.

For example, in order to draw the image represented by myImageData in the upper left corner of the scene, you can write the following code:

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


There is the following element

<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);
Copy after login

Application 2: Video solid color background filtering

Today, we use getImageData to filter out the solid color background.

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;
  }
};
Copy after login

Application 3: Image grayscale and inverted color

In this example, we iterate through all pixels to change their values. Then we put the modified pixel array back into the canvas through putImageData(). The invert function just subtracts the maximum color value of the color by 255. The grayscale function just uses the average of red, green and blue. You can also use a weighted average, such as the formula 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);
}
Copy after login


Application four-scaling and anti-aliasing

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);
}
Copy after login

Application five-canvas hand-drawing and downloading pictures

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);
Copy after login

I believe after reading these cases You have mastered the method. For more exciting information, please pay attention to other related articles on the php Chinese website!


Related reading:

How to make the loading effect of CSS3

How to make it with css3 Icon effect

How to convert CSS encoding

The above is the detailed content of How to use ImageData of canvas. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template