Canvas canvas image drawing foundation
Draw image
grammar
- ctx.drawImage(image,dx,dy);
- ctx.drawImage(image,dx,dy,dw,dh);
- ctx.drawImage(image,sx,sy,sw,sh,dx,dy,dw,dh);
This method can draw an image into the Canvas (source image - target image).
parameter
- dx = origin coordinates of the target image (X axis)
- dy) origin coordinates of the target image (Y-axis)
- sx# origin coordinates of the source image (X axis)
- sy# origin coordinates of the source image (Y axis)
- sh # size (height) of the source image
- sw) size (width) of the source image
- dw - size (width) of the target image
- dh is the size (height) of the target image
- Image - the image drawn on the canvas( HTMLImageElement)
explain
[1] drawImage The first argument to the method can be HTMLImageElement Type of image or HTMLCanvasElement Type Canvas object perhaps HTMLVideoElement Type of video object. [2] drawImage Method can convert an image(Canvas object 」Video frame)Draw whole or part of to Canvas When drawing to the canvas, you can Arbitrarily specify where to draw and the scale.
Illustration
Example-01
<canvas id="canvas" width="800" height="1000"></canvas> <script> //[1] Get canvas and corresponding context var ctx = document.getElementById("canvas").getContext("2d"); //[2] Create an Image and set up a data source var img = new Image(); img.src = "PQ.png"; img.alt = "I am a pig,My family are pigs~"; //[3] After the listening picture is loaded, draw the picture to the canvas img.onload = function(){ //Demo 001 //Draw the picture on the Canvas, the origin coordinate of the drawing reference is (0,0), and scale the size of the picture to 200 in width and height ctx.drawImage(img,0,0,200,200) //Demo 002 //Cut (the reference coordinate of the cutting starting point is [150,0]) a part of the picture (the right half) is drawn on the canvas, and the origin coordinate of the drawing reference is (205,0) ctx.drawImage(img,150,0,150,300,205,0,150,300) //Demo 003 //Draw the picture (300 * 300) to the specified position on the canvas, and the origin coordinate of the drawing reference is (360,0) ctx.drawImage(img,360,0); } </script>
Example-02
<canvas id="canvas" width="2000" height="800"></canvas> <script> //[1] Get the Canvas in the page and the corresponding context var ctx = document.getElementById("canvas").getContext("2d"); //[2] Create an Image and set up a data source var img = new Image(); img.src = "hero.png"; //[3] Define variables (width, height and equal number of source pictures) var width = 1620,height = 240,equalDivisionCount = 7; //[4] Monitor Image loading img.onload = function(){ //[5] After the Image is loaded, draw the complete Image to the canvas first ctx.drawImage(img,0,0) //[6] Control the drawing (animation) of the image through the timer var i = 0; var timer = setInterval(function () { ctx.canvas.width = 2000; ctx.drawImage( img, width * i/equalDivisionCount,0, width/equalDivisionCount,height, width * i/equalDivisionCount,0, width/equalDivisionCount,height ); i++; if(i == 7) { clearInterval(timer); ctx.drawImage(img,0,0) } },200); } </script>
Convert Canvas canvas to image
Syntax canvas toDataURL()
This method is used to convert the contents of the Canvas canvas into an image.
Example
<canvas id="canvas" width="200" height="200"></canvas> <img src="" alt=""> <script> //[1] Gets the img tag in the page var oImage = document.getElementsByTagName("img")[0]; //[2] Gets the canvas tag in the page var canvas = document.getElementById("canvas"); //[3] Gets the context object of the canvas var ctx = canvas.getContext("2d"); //[4] Create Image image object var img = new Image(); //[5] Set the data source of the Image img.src = "PQ.png"; //[6] Monitor Image loading img.onload = function () { //[7] Draw the image into the Canvas ctx.drawImage(img, 0,0,200,200); //[8] Convert canvas to image, save and display oImage.src = canvas.toDataURL(); } </script>
**Remarks * * the toDataURL method of the Canvas tag object converts the Canvas into an image represented by Base64. For knowledge points related to Base64 coding, please refer to [data security series Base64]( http://wendingding.com/2018/07/31/%E6%95%B0%E6%8D%AE%E5%AE%89%E5%85%A8%E7%B3%BB%E5%88%97%20Base64/ ).
Syntax CTX getImageData(dx,dy,w,h)
Gets (copies) the pixel data of the specified rectangular area on the Canvas.
putImageData
Syntax CTX putImageData(imgData,dx,dy,[dirtyX],[dirtyY],[dirtyWidth],[dirtyHeight]);
This method is used to put the image data of the specified ImageData object back on the canvas.
parameter
- imgData specifies the ImageData object to put back on the canvas
- dx # the position (X coordinate) where the canvas is drawn, In pixels.
- dy) where to draw to the canvas (Y coordinate), In pixels.
- The position (X coordinate) of the imageData object intercepted by the dirtyX # part is 0 by default.
- The location (Y coordinate) of the imageData object intercepted by the dirtyY # part is 0 by default.
- The dirtyWidth} section intercepts the size (width) of the imageData object. The default is the width of the whole image.
- The dirtyHeight section intercepts the size (height) of the imageData object. The default is the height of the whole image.
Note the last four parameters of putImageData() method are optional. Either 3 parameters or 7 parameters are passed when calling.
Example
<canvas id="canvas" width="1000" height="400"></canvas> <script> //[1] Gets the Canvas canvas in the page var canvas = document.getElementById("canvas"); //[2] Gets the context object of Cnavas var ctx = canvas.getContext("2d"); //[3] Draw a blank filled rectangle at the specified position on the canvas ctx.fillStyle="#f9f"; ctx.fillRect(10,10,100,50); //Demo 001 //[4] Obtain the image data of the specified rectangular area in the canvas, and then put it in the specified position of the canvas (equivalent to copying) ctx.putImageData(ctx.getImageData(10,10,100,50),120,10); ctx.putImageData(ctx.getImageData(10,10,100,50),230,10,0,0,50,50); //[5] Create Image var img = new Image(); //[6] Set the data source of the Image img.src = "Yu.jpg"; //[7] Monitor Image loading img.onload = function () { //[8] Draw the image into the Canvas ctx.drawImage(img,10,70,100,60); //Demo 002 //[9] Obtain the image data of the specified rectangular area in the canvas, and then put it in the specified position of the canvas (test parameters) var imgData = ctx.getImageData(10,70,100,60); /* * 3 Case of two parameters * First parameter: imageData object * Second parameter: where to draw to the canvas (X) * Third parameter: draw to canvas position (Y) * */ ctx.putImageData(imgData,120,70); /* * 7 Case of two parameters * First parameter: imageData object * Second parameter: where to draw to the canvas (X) * Third parameter: draw to canvas position (Y) * The fourth parameter: the location where the imageData object is partially intercepted (X) * The fifth parameter: the location where the imageData object is partially intercepted (Y) * The sixth parameter: the size (width) of the partially intercepted imageData object * Size of imageData object (seventh parameter) * */ ctx.putImageData(imgData,230,70,50,0,100,60); ctx.putImageData(imgData,340,70,0,30,100,60); ctx.putImageData(imgData,450,70,0,0,100,30); ctx.putImageData(imgData,560,70,0,0,100,60); } </script>
**Note * * when specifying the Canvas offset, it needs to be in CSS pixels, but when specifying the rectangular area in the image data, it needs to be in set pixels. In addition, it should be noted that the area determined by the last four parameters of putImageData is called "dirty Rectangle". When the browser assigns the dirty rectangle to the Canvas canvas, the device pixels will be converted to CSS pixels by default.
ImageData object
The getImageData() method described above returns an object of ImageData type, which contains three attributes: width, height and data. Where width represents the width of image data in device pixels, while height represents the height of data. In addition, data is an array containing the values of each device pixel.
In the ImageData object, each array element contained in the data attribute corresponds to the corresponding pixel value in the image data. There are four aspects of information in each pixel, representing the color of the current pixel respectively( RGB - Red 」Green 」Blue )And transparency( A - alpha ). These information are represented by integers containing 8 binary bits (the eighth power of 2), with values ranging from 0 to 255.
in other words, ImageData.data[0]It represents a red value, ImageData.data[1]It represents a green value, ImageData.data[2]It represents a blue value, ImageData.data[3]Represents the transparency value. move in circles(If the length of the data array is n,that`ImageData.data[n-4]`Represents the red value, and so on).
createImageData method
grammar
- ctx.createImageData(w,h);
- ctx.createImageData(imageDataOther);
This method creates a new blank ImageData object according to the specified width and height (the width and height of the target object).
parameter
- w the specified width.
- h the specified height.
- imageDataOther refers to the image data.
Example-01
<canvas id="canvas" width="600" height="400"></canvas> <script> //[1] Get the Canvas canvas and the corresponding context in the page var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); //[2] Create ImageData object var imageData = ctx.createImageData(2,2); console.log(imageData); /* * data: Uint8ClampedArray(16) [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] * height: 2 * width: 2 */ //[3] Draw a red rectangle in the canvas ctx.fillStyle = "red"; ctx.fillRect(0,0,20,20); //[4] Gets the image data of the specified area in the canvas imageData = ctx.getImageData(0,0,2,2); console.log(imageData); /* * data: Uint8ClampedArray(16) [255,0,0,255,255,0,0,255,255,0,0,255,255,0,0,255] * height: 2 * width: 2 */ </script>
The default pixel value for new objects, transparent black, is expressed as (0, 0 , 0 , 0) . The first three items represent color, and the last item represents transparency. color/alpha exists in the form of an array, and the size of the array is four times that of the ImageData object.
Example description
In the code above ctx.createImageData(2,2)Indicates that you want to create 2 * 2 Blank area ImageData Object. Obtained after calling the method ImageData Object has 2 * 2 = 4 Pixels, each represented by four elements in the array. Print ImageData Property([4])Displayed as: data:Uint8ClampedArray(16) [255,0,0,255,255,0,0,255,255,0,0,255,255,0,0,255] We observe the subscript 0~3 This set of data: 255,0,0,255,The result of trying to give a label is 255(Red),0(Green),0(Blue),255(alpha)
Through the above analysis, after mastering the internal representation structure of ImageData, we found that the display of any pixel of the image can be accurately controlled through the code, including the RGB color and transparency of the pixel can be controlled, and any filter effect can be simply realized by combining the corresponding algorithms and calculation formulas.
Example-02
<canvas id="canvas" height="400" width="600"></canvas> <script> //[1] Get canvas and drawing context var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); //[2] Create ImageData object (10 * 10) var imgData = ctx.createImageData(10,10); //[3] Sets the ImageData image to be filled with red var length = imgData.data.length; for (var i = 0; i<length; i+=4) { imgData.data[i+0] = 255; imgData.data[i+1] = 0; imgData.data[i+2] = 0; imgData.data[i+3] = 255; } //[4] Draw the image data onto the canvas ctx.putImageData(imgData,0,0); </script>