canvas color pixel operations take writes pixel data stored image scaling and anti-aliasing

About blog

In HTML5 canvas allows us to directly operate the pixel, we can manipulate the pixel data ImageData object to read or write data in the object array. Here also describes how to control the image to smoothing (anti-aliasing) and how to save an image from a Canvas canvas.

  • imageData objects
  • Reading or writing the object imageDate
  • Scaling and anti-aliasing
  • save Picture

ImageData objects

ImageData object stored canvas object in the real pixel data, comprising the following read-only properties

  • iwidth: pictures of width in px
  • height: image height in px
  • data: Uint8ClampedArray type one-dimensional array, comprising a RGBA format, integer data, the range (including 255) between 0 and 255.
  • property returns a pixel data array Uint8ClampedArray, as it can be used to view the original pixel data. Each pixel value 1bytes 4 (according to the red, green, blue and transparent order value; this is the "RGBA" format) represented. Each part of the color values ​​represented by 0-255. Each portion is assigned to a consecutive indexes in the array, the red portion of the upper left pixel location in the array index 0. The pixels are processed from left to right, then down, through the entire array.
  • Obtaining i-th row j-th column of R / G / B / A value:
imageData.data[((行数-1)*imageData.width + (列数-1))*4 - 1 + 1/2/3/4];
  • Gets the size of the pixel array Uint8ClampedArray:
var numBytes = imageData.data.length;

Creating a ImageData objects

In general, to create a ImageData object, we can use createImageData method:

  • var myImageData = ctx.createImageData (width, height): creates a new dimension of width, height of ImageData object, all the pixels are preset to transparent black.
  • var myImageData = ctx.createImageData (anotherImageData): Create an ImageData object of the same pixel is specified anotherImageData object. The new object is preset to all pixels transparent black. This is not to copy the picture data.
var myImageData = ctx.createImageData(width, height);
var myImageData = ctx.createImageData(anotherImageData);

Gets ImageData objects in the scene canvas area

We can obtain pixel data in a specified area of ​​the canvas by getImageData method:

  • getImageData (x, y, width, height): Returns a ImageData object that describes the (x, y, x + width, y + height) of the pixel region

Example: eyedropper

This example, we will return to the pixels of the mouse position:

  • Get the mouse position x, y
  • Gets the position of the object ImageData
  • Get Object Data
  • Return the data, and with the paint color RGBA values
var img=new Image();
window.onload=function()
{
    img.src="spiderMan.jpg";//获取图片
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext('2d');
    img.onload=function()
    {
        ctx.drawImage(img,0,0,400,300);//画出图片
        //获取ImageData对象
        canvas.addEventListener("mousemove",function(e)
        {
            var x=e.layerX;
            var y=e.layerY;//获取坐标
            var imageData=ctx.getImageData(x,y,1,1);//获取x,y处像素1*1的图片
            var data=imageData.data;//获取像素数据
            var r=data[0];
            var g=data[1];
            var b=data[2];
            var a=data[3];
            var color="rgba("+r+","+g+","+b+","+a+")";
            ctx.clearRect(0,305,400,400)
            ctx.save();
            ctx.fillStyle=color;
            ctx.fillRect(0,305,100,40);//绘制矩形
            ctx.font="15px 幼圆";
            ctx.save();
            ctx.fillStyle=" #7B68EE";
            ctx.fillRect(0,375,250,40);
            ctx.restore();
            ctx.fillText("光标处像素="+color,0,400);
            ctx.restore();
        })
    }
}

Here Insert Picture Description

Pixel data is written in the canvas scene

We obtain the pixel data of the designated region by the canvas getImageData method, but can also be used putImageData () method writes the pixel write the canvas

  • putImageData (imageData, x, y): The picture drawn ImageData object represents the x, y position
  • ImageData.data directly modify the object can be changed ImageData

For example putImageData

After the following we will manipulate an image pixel, the pixel value is removed, for its grayscale and inverted operation, we set the two functions to achieve grayscale and invert:

  • grayscale gradation processing : x = 0.299r + 0.587g + 0.114b
function grayscale()//灰度
{
    for(var i=0;i<data.length;i+=4)
    {
        avg=0.299*data[i] + 0.587*data[i+1] + 0.114*data[i+2];
        data[i]=data[i+1]=data[i+2]=avg;
    }
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.putImageData(imageData,0,0);
}
  • invert the inverted process : x = 255-i
function intervar()//反相
{
    for(var i=0;i<data.length;i+=4)
    {
        data[i]=255-data[i];//r
        data[i+1]=255-data[i+1];//g
        data[i+2]=255-data[i+2];//b
    }
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.putImageData(imageData,0,0);
}

Finally, add a listener

  var invertbtn = document.getElementById('invertbtn');
  invertbtn.addEventListener('click', intervar);

  var grayscalebtn = document.getElementById('grayscalebtn');
  grayscalebtn.addEventListener('click', grayscale);

Here Insert Picture Description

Here Insert Picture Description
Here Insert Picture Description

Scaling and anti-aliasing

Canvas zoom operation on the image, we have already introduced, is achieved by drawImage (x, y, w, h), default zoom antialiasing process, if we want to get rid antialiasing, see specific pixels, may be used imageSmoothingEnabled properties:

  • imageSmoothingEnabled serrated: If true, then show anti-aliasing, is false impressions sawtooth

For example scaling and anti-aliasing

var img=new Image();
img.src="../纸飞机.jpg";
var canvas;
var able=1;
img.onload=function()
{
    draw(this);
}
function toggleSmoothing()
{
    able=able?false:true;
    ctx.imageSmoothingEnabled=able;
}
function show(e)
{
    var x=e.layerX;
    var y=e.layerY;//获取坐标
    ctx.clearRect(500,0,200,200);
    ctx.drawImage(canvas,Math.abs(x-5),Math.abs(y-5),10,10,500,0,200,200);
}
function draw(img) {
  canvas = document.getElementById('canvas');
  ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0,480,300);
  img.style.display = 'none';

  var smoothbtn = document.getElementById('smoothbtn');//获取区域
  smoothbtn.addEventListener('click',toggleSmoothing);
  canvas.addEventListener('mousemove',show);
}

Here Insert Picture Description
Here Insert Picture Description

save Picture

HTMLCanvasElement a toDataURL () method, which is very useful when saving pictures. It returns a data link type parameter is specified image format contains performance. Returns the picture resolution is 96dpi.

  • canvas.toDataURL ( 'Image / PNG') : the default setting. Create a PNG image.
  • canvas.toDataURL ( 'Image / jpeg', at Quality) : create a JPG picture. You can optionally provide quality goods from 0-1 with 1 being the best quality, 0 substantially not discriminate but a relatively small file size.
    When you generate a data link from the canvas, for example, you can use it for any <image> element, or put it in a download hyperlink property was saved locally for
  • canvas.toBlob (callback, of the type, encoderOptions) : This creates a representative picture of the Blob on the canvas like.

Save the picture with a hyperlink:

We slightly modified the above picture, and insert a hyperlink

var img=new Image();
img.src="../纸飞机.jpg";
var canvas;
var able=1;
img.onload=function()
{
    draw(this);
}
function toggleSmoothing()
{
    able=able?false:true;
    ctx.imageSmoothingEnabled=able;
}
function show(e)
{
    var x=e.layerX;
    var y=e.layerY;//获取坐标
    ctx.clearRect(500,0,200,200);
    ctx.drawImage(canvas,Math.abs(x-5),Math.abs(y-5),10,10,500,0,200,200);
}
function draw(img) {
  canvas = document.getElementById('canvas');
  ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0,480,300);
  img.style.display = 'none';

  var smoothbtn = document.getElementById('smoothbtn');//获取区域
  smoothbtn.addEventListener('click',toggleSmoothing);
  canvas.addEventListener('mousemove',show);
  canvas.addEventListener("click",function(){
    var area=document.getElementsByTagName("a")[0];
    area.setAttribute("href",canvas.toDataURL("纸飞机",1));
  })
}

When the picture is clicked, it will generate a toDataURL objects, click the hyperlink will download pictures:
Here Insert Picture Description
Here Insert Picture Description
Pictures download is complete

Published 123 original articles · won praise 136 · views 30000 +

Guess you like

Origin blog.csdn.net/weixin_44307065/article/details/104110109