An overview of the

A Canvas is used to generate images in real time on a web page and manipulate the image content. Basically, it is a bitmap that can be manipulated with JavaScript.

Begin to use


  1. Create a new<canvas>Page elements.
<canvas id="myCanvas" width="400" height="200"Your browser does not support canvas! </canvas>Copy the code
  • Alternative content
    • support<canvas>The browser will ignore the contents contained in the container and render the canvas normally.
    • Does not support<canvas>The browser will display the alternate content
  • widthandheight
    • The default width is 300 pixels and the default height is 150 pixels.
    • htmlAttribute setwidth/heightAffects only the canvas itself and does not affect the canvas content
    • cssAttribute setwidth/height“Will not only affect the height and width of the canvas itself, but also make the contents of the canvas scale equally (scaling refers to the default size of the canvas).
  1. <canvas>The element just creates a fixed sizeThe canvas, to draw content on it, you need to usegetContext()How to find itRender context.
Var canvas = document.getelementById ('myCanvas'); // Create a render contextif (canvas.getContext) {
  var ctx = canvas.getContext('2d');
}
Copy the code

In the above code, the getContext method specifies the parameter 2d, indicating that the Canvas node is used to generate 2d patterns (i.e. flat patterns). If the parameter is WebGL, it means that it is used to generate 3D images (i.e. stereoscopic patterns), which is actually called the WebGL API alone.

The drawing method

Canvas provides a flat space for drawing. Each point in this space has its own coordinates, x for abscissa and y for vertical. The origin (0, 0) is located in the upper left corner of the image, and the forward direction of the x axis is the origin to the right, and the forward direction of the y axis is the origin to the right

Styles and colors

  • fillStyle: Sets the fill color, black by default
  • strokeStyle: Sets the outline color, black by default
  • lineWidth: Sets the line width to any positive integer. The default value is 1.0.
  • lineJoin: Controls how lines intersect (defaultmiter)
    • round: rounded corners
    • bevel: bevel
    • miter: the right Angle
  • lineCap: The shape of the end of the line segment (default isbutt)
    • butt: Line segment ends in a square.
    • round: Line segment ends in a circle
    • square: The end of the line segment ends in a square, but adds a rectangular area the width of the line segment and half the height of the line segment

Save (), restore(), beginPath()

  • Style containers
    • Every time the style API is called, a check is made into the style container
    • callsave(), pushes the state in the style container to save the context
    • callrestore(), pops the top state of the style stack into the style container and restores to the last saved context
// Use the save method to save the current setting ctx.save(); ctx.shadowOffsetX = 10; ctx.shadowOffsetY = 10; ctx.shadowBlur = 5; ctx.shadowColor ='rgba (0,0,0,0.5)'; // Draw a shaded rectangle ctx.fillstyle ='#CC0000'; CTX. FillRect,10,150,100 (10); Ctx.restore (); // Use the restore method to restore the set ctx.restore(); // Draw a rectangle with no shadows ctx.fillstyle ='# 000000'; CTX. FillRect,10,150,100 (180);Copy the code
  • Path to the container
    • Every time you call the path API, you check into the path container
    • callbeginPathEmpty the entire path container
ctx.save(); // Set the style ctx.beginPath(); // Set the path ctx.restore();Copy the code

transform

  • translate(x, y)Move the canvas origin to (x,y), translate iscumulativethe
  • rotate(angle)Around:The originRotate the image Angle (clockwise), rotate iscumulativethe
  • scale(x, y): Zoom the image; X and y are scaling factors (positive) for the horizontal and vertical axes respectively, and scale iscumulativethe
    • Smaller than 1.0: shrink
    • Greater than 1.0: magnification
    • Nothing at 1.0

(1) Draw a rectangle

Ctx.fillrect (x, y, width, height); ctx.fillrect (x, y, width, height); // Border rectangle, default 1px black. ctx.strokeRect(x, y, width, height); // Clear the specified rectangle and make it transparent ctx.clearRect(x, y, width, height); // When drawing dynamic effects, it is used to clear the entire canvasCopy the code
  • rect(x, y, width, height): Draws a rectangular path

(2) Draw paths

Ctx.beginpath () // The beginning of the path (line), usually after the above command executes ctx.moveto (x, y) // the end of the line ctx.lineto (x, y) // Close the path, not required, If the end of the line is the same as the beginning, it will automatically close. Ctx.closepath () // Draws the outline (border) with the line ctx.stroke() // Does not automatically call closePath() // Fills the area (solid) with the path ctx.fill() // automatically calls closePath()Copy the code

Example: Draw a triangle

ctx.beginPath(); ctx.moveTo(75, 50); Ctx.lineto (100, 75); ctx.lineTo(100, 25); ctx.fill(); // The path is automatically closed and filled with black by default.Copy the code
  • quadraticCurveTo(cp1x, cp1y, x, y): Draw a quadratic Bezier curve, cp1x,cp1y as a control point, starting point as moveto, x,y as the end point.
  • bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y): Draw bezier curves three times, cp1x,cp1y are control points 1, cp2X,cp2y are control points 2, starting point is the point specified when moveto, x,y are the end points.
  • ctx.isPointInPath(x, y): Checks whether check points are included in the current path
    • X: indicates the x coordinate of the detection point
    • Y: indicates the y coordinate of the detection point
    • Note that this method only works on the newly drawn canvas image

(3) Draw text

  • fillText(string, x, y): fills the specified text at the specified (x,y) position
    • Four parameters: a text string, the x and y coordinates of the starting point, and the optional maximum pixel width.
  • strokeText(string, x, y): fills the specified text at the specified (x,y) position
// To set the font, you must have the size and font ctx.font ="Bold 20px Arial"; // Set the alignment. Possible values are left and right center ctx.textalign ="left"; // Set the fill color ctx.fillstyle ="# 008600"; // Set the font content and the position on the canvas ctx.fillText("Hello!", 10, 50); // Draw the hollow word ctx.stroketext ("Hello!", 10, 100); 
Copy the code
  • measureText()Method: Return a TextMetrics object containing information about the size of the text (such as the width of the text)

(4) Draw circles and sectors

// Draw the circle ctx.arc(x, y, r, start, end,true/false) //(x, y) center, r radius, start and end are the starting and ending angles,falseRepresents clockwise (default),trueIt means counterclockwise. // draw arc ctx.arcTo(x1, y1, x2, y2, r); // The current endpoint, (x1,y1), and (x2,y2) arc, where r is the radius.Copy the code

Example: Draw a solid circle

ctx.beginPath(); 
ctx.arc(60, 60, 50, 0, Math.PI*2, true); 
ctx.fillStyle = "# 000000"; 
ctx.fill();
Copy the code

Example: Draw hollow circles

ctx.beginPath(); 
ctx.arc(60, 60, 50, 0, Math.PI*2, true); CTX. Our lineWidth = 1.0; ctx.strokeStyle ="# 000"; 
ctx.stroke();
Copy the code

(5) Set the shadow

ctx.shadowOffsetX = 10; // Set the horizontal shift ctx.shadowOffsetY = 10; // Set vertical shift ctx.shadowBlur = 5; // Set the blur ctx.shadowColor ="Rgba (0,0,0,0.5)"; // Set the shadow color ctx.fillstyle ="#CC0000"; CTX. FillRect,10,200,100 (10);Copy the code

(6) Set the gradient

  • createLinearGradient(x1, y1, x2, y2)Create a Canvas gradient (linear gradient)
    • Gradient starting (x1,y1) and ending (x2,y2)
  • gradient.addColorStop(position, color)
    • gradient:createLinearGradientThe return value of the
    • addColorStopThe method takes two parameters:
      • positionThe parameter must be a number between 0.0 and 1.0, indicating the relative position of the color in the gradient. For example, 0.5 indicates that the color will appear in the center.
      • colorThe argument must be a valid CSS color value, such as #FFF, rgba(0,0,0,1), etc
Var myGradient = ctx.createlineargradient (0, 0, 0, 160); // Create a canvas linear gradient and return an instance of 'CanvasGradient' object. myGradient.addColorStop(0,"#BABABA"); 

myGradient.addColorStop(1, "# 636363"); // Draw the rectangle ctx.fillStyle = myGradient; CTX. FillRect,10,200,100 (10);Copy the code
  • createRadialGradient(x1, y1, r1, x2, y2, r2)Canvas gradient (Radial gradient)
    • The first three parameters define another circle with the origin of (x1,y1) and radius R1
    • The last three parameters define another circle with the origin of (x2,y2) and radius of R2

Image processing method

DrawImage () method

The Canvas API allows you to insert an image file into the Canvas by reading the image and redrawing it inside the Canvas using the drawImage method.

  • When a canvas manipulates a picture, it must wait until the picture is loaded
  • drawImage(image, x, y, width, height)
    • image: DOM element of the image file
    • xy: Draws the starting coordinates of the image
    • widthheight: Target width and height
var image = new Image();
image.src = 'image.png';

image.onload = function() {
  var canvas = document.createElement('canvas');
  canvas.width = image.width;
  canvas.height = image.height;
  canvas.getContext('2d').drawImage(image, 0, 0); / / insert the bottom of the page document. The body. The appendChild (image);return canvas;
}


Copy the code

CreatePattern () method: Sets the background mode

  • createPattern(image, repetition)
    • image: image source
    • epetition
      • repeat
      • repeat-x
      • repeat-y
      • no-repeat

In general, we set the fillStyle value to the object returned by createPattern, which only indicates that duplicate images are displayed within a specific area.

GetImageData () method, putImageData() method

With the getImageData method and putImageData method, each pixel can be processed to manipulate the image content.

  • ctx.getImageData(sx, sy, sw, sh): Gets an object that contains the pixel data of the canvas sceneImageDataObject, which represents the object data of the canvas area
    • parameter
      • Sx: X coordinates of the image region to be extracted.
      • Sy: Y coordinates of the image region to be extracted.
      • Sw: Width of pixels to be extracted.
      • Sh: pixel height to be extracted.
    • ImageDataObject stores the real pixel data of the Canvas object, which contains the following read-only properties:
      • width: Image width, in pixels
      • height: Image height, in pixels
      • dataUint8ClampedArray one-dimensional array of type, containingRGBAInteger data in the range 0 to 255 inclusive
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
Copy the code
  • putImageData(myImageData, dx, dy): Draws the image data onto the canvas
context.putImageData(imageData, 0, 0);
Copy the code
  • Routine code

Assuming filter is a function that processes pixels, the entire Canvas processing process can be represented by the following code.

if (canvas.width > 0 && canvas.height > 0) {
    var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
    
    filter(imageData);

    context.putImageData(imageData, 0, 0);

}
Copy the code

CreateImageData () method

  • ctx.createImageData(width, height): Creates an ImageData object
    • Width: ImageData Width of the new object.
    • Height: ImageData Height of the new object.
    • The default creation is transparent

synthetic

  • globalAlpha = value: Sets global transparency. This property affects the transparency of all graphics in the canvas
    • Valid values range from 0.0 (completely transparent) to 1.0 (completely opaque)
    • The default is 1.0
  • globalCompositeOperation: Overlay composition (source– > new image (source); Destination –> Graph already drawn (destination)
    • source-over(Default): The source is above and the new image is higher
    • source-in: Leaving only the overlap between the source and the target (that part of the source)
    • source-out: Leaves only the portion of the source that exceeds the target
    • source-atop: Cut the overflow part of the source
    • destination-over: The target is on top, the old image is higher level
    • destination-in: Leaving only the overlap between source and target (that part of target)
    • destination-out: Leaves only the portion of the target that exceeds the source
    • destination-atop: Cut out the overflow of the target

ToDataURL (): Exports the canvas as an image

Notice the method on the Canvas element interface

function convertCanvasToImage(canvas) {
  var image = new Image();
  image.src = canvas.toDataURL('image/png');
  return image;
}
Copy the code

The code above converts Canvas data into a PNG data URI.

Common effect

Gray scale effect

Grayscale is the arithmetic average of red, green and blue pixel values. Assuming d[I] is the red value of a pixel in the pixel array, d[I +1] is the green value, d[I +2] is the blue value, and D [I +3] is the alpha channel value. The grayscale algorithm is to add the red, green, and blue values, divide by 3, and write the result back into the array.

grayscale = function (pixels) {

	var d = pixels.data;

    for (var i = 0; i < d.length; i += 4) {
      var r = d[i];
      var g = d[i + 1];
      var b = d[i + 2];
      d[i] = d[i + 1] = d[i + 2] = (r+g+b)/3;
    }

    return pixels;

};
Copy the code

Effect of restoring ancient ways

Retro effect (SEPIA) is to take the three pixels of red, green and blue, respectively, a weighted average of these three values, so that the image has an ancient effect.

sepia = function (pixels) {

    var d = pixels.data;

    for(var i = 0; i < d.length; i += 4) { var r = d[i]; var g = d[i + 1]; var b = d[i + 2]; D [I] = (r * 0.393)+(g * 0.769)+(b * 0.189); d[I] = (r * 0.393)+(g * 0.769)+(b * 0.189); / / red [I + 1) = d (r * 0.349) + (g * 0.686) + (b * 0.168); / / green [I + 2) = d (r * 0.272) + (g * 0.534) + (b * 0.131); // blue }return pixels;

};
Copy the code