How to Use Canvas to process images,

Source: Internet
Author: User

How to Use Canvas to process images,

Canvas. The <canvas> element is added to html5. you can use JavaScript to dynamically draw images on the Canvas.

Today, we will not talk about Canvas graphics, but about how to process images.

The general process is very simple, mainly divided into the following three steps:

Yes, it's as easy as loading an elephant into a refrigerator. Haha.

I. Main APIs

The main Canvas APIs used throughout the process include:

  1. Draw an image: drawImage ()
  2. Get image data: getImageData ()
  3. Rewrite image data: putImageData ()
  4. Export image: toDataURL ()

1. drawImage ()

As the name suggests, this method is used to draw images on the Canvas. There are three specific usage methods:

① Position the image on the canvas: context. drawImage (img, x, y)
② Locate the image on the canvas and specify the width and height of the image: context. drawImage (img, x, y, width, height)
③ Cut the image and locate the cut part on the canvas: context. drawImage (img, sx, sy, swidth, sheight, x, y, width, height)

The preceding parameter values are described as follows:

Parameters Description
Img Specifies the image, canvas, or video to be used.
Sx Optional. The x coordinate position of the Start cut.
Sy Optional. Y coordinate position of the Start cut.
Swidth Optional. Width of the cut image.
Sheight Optional. The height of the cut image.
X Place the x coordinate position of the image on the canvas.
Y Place the y coordinate position of the image on the canvas.
Width Optional. The width of the image to be used. (Stretch or zoom out an image)
Height Optional. The height of the image to be used. (Stretch or zoom out an image)

2. getImageData ()

This method is used to obtain image data from the Canvas. The usage is as follows:

Obtain the pixel data within the specified rectangle of the canvas: var ImageData = context. getImageData (x, y, width, height)
The preceding parameter values are described as follows:

Parameters Description
X The x coordinate at the upper left corner of the replication start.
Y Start copying the y coordinate at the upper left corner.
Width The width of the area of the rectangle to be copied.
Height The height of the rectangle area to be copied.

This method will return an ImageData object. The object has three attributes: width, height, and data, and we mainly use this data array, because it stores the data of each pixel in the image. With this data, we can process it and then rewrite it to the Canvas. This allows us to process and convert images. For the specific usage of the data array, we can see in the following instance.

3. putImageData ()

This method is simple. It is used to overwrite image data to the Canvas. The usage is as follows:

context.putImageData(imgData,x,y,dirtyX,dirtyY,dirtyWidth,dirtyHeight)

The preceding parameter values are described as follows:

Parameters Description
ImgData Specifies the ImageData object to be put back into the canvas.
X X coordinate in pixels in the upper left corner of the ImageData object.
Y Y coordinate in the upper left corner of the ImageData object, in pixels.
DirtyX Optional. Horizontal value (x), in pixels, where the image is placed on the canvas.
DirtyY Optional. Horizontal value (y), in pixels, where the image is placed on the canvas.
DirtyWidth Optional. The width used to draw an image on the canvas.
DirtyHeight Optional. The height used to draw an image on the canvas.

4. toDataURL ()

This method is different from the preceding three methods. It is a Canvas object method that returns a string containing data URI, this string can be directly used as the image path address in the src attribute of the label. The usage is as follows:

var dataURL = canvas.toDataURL(type, encoderOptions);

The preceding parameter values are described as follows:

Parameters Description
Type Optional. Image format. The default format is image/png.
EncoderOptions Optional. When the image format is image/jpeg or image/webp, you can select the image quality from 0 to 1. If the value range is exceeded, the default value 0.92 is used. Other parameters are ignored.

Ii. Image Processing instances

In this example, the code is used to briefly describe how to process a color image into a black/white image.

<! -- HTML --> <canvas id = "canvas" width = "600" height = "600"> </canvas> <input id = "handle" type = "button" value = "process image"/> <input id = "create" type = "button" value = "generate image"/> <div id = "result"> </div>
// JavaScriptwindow. onload = function () {var canvas = document. getElementById ("canvas"), // obtain the Canvas object context = canvas. getContext ('2d '); // get the 2d context object. Most Canvas APIs use this object method var image = new Image (); // define an image object image. src = 'imgs/img.jpg '; image. onload = function () {// note this! All subsequent operations must be performed after the image is loaded successfully. Otherwise, the image processing will be ineffective. drawImage (image,); // draw the image from the upper left corner () of the Canvas. The default size is var handle = document. getElementById ("handle"); var create = document. getElementById ("create"); handle. onclick = function () {// click the "process image" button to process the image var imgData = context. getImageData (0, 0, canvas. width, canvas. height); // obtain the image data object var data = imgData. data; // obtain an array of image data. each pixel in the array is saved with four elements, indicating that the values of red, green, blue, and transparency are var average = 0; for (var I = 0; I <data. length; I + = 4) {average = Math. floor (data [I] + data [I + 1] + data [I + 2])/3 ); // calculate the average values of red, green, and blue to obtain the gray value data [I] = data [I + 1] = data [I + 2] = average; rewrite the color value of each pixel} imgData. data = data; context. putImageData (imgData,); // rewrite the processed image data to the Canvas, and the image in the Canvas becomes black and white}; create. onclick = function () {// click the "generate image" button to export the image var imgSrc = canvas. toDataURL (); // obtain the Image's DataURL var newImg = new Image (); var result = document. getElementById ("result"); newImg. src = imgSrc; // assign the image path to src result. innerHTML = ''; result. appendChild (newImg );};};};

The above Code may not be well written, and it does not seem so easy to understand. It is best to write it yourself, so that you can have a deeper understanding of yourself.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.