This is the 22nd day of my participation in the August More Text Challenge

Canvas related methods and their usage

arc()

Draw arcs and circles.

/** x: x coordinates of the center of the arc y: y coordinates of the center of the arc radius: the radius of the arc startAngle: the starting point of the arc, the calculation of the X-axis direction, the unit of radian Bool Optional: true: arc is drawn counterclockwise false: arc is drawn clockwise. The default value is false */
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
Copy the code

Example:

ctx.beginPath();
ctx.arc(75.75.50.0.10);
ctx.stroke();
// the page will display a radius of 50 ⚪
Copy the code

Effect:

arcTo()

Draws an arc path based on the control point and radius. Use the current stroke point (the stop of the previous function such as moveTo or lineTo). Draw an arc path between two tangent lines based on the line connecting the current stroke point to the given control point 1, and the line connecting control point 1 to control point 2, as a tangent line to a circle using the specified radius.

/** x1: x-coordinate of the first control point y1: y-coordinate of the first control point x2: x-coordinate of the second control point y2: y-coordinate of the second control point RADIUS: radius of the arc */
ctx.arcTo(x1, y1, x2, y2, radius)
Copy the code

Example:

ctx.beginPath();
ctx.moveTo(50.50);
ctx.arcTo(65.150.202.57.40);
// Note that the data in lineTo should be consistent with the coordinates of the second arcTo control point
ctx.lineTo(202.57);
ctx.stroke();
Copy the code

Effect:

beginPath()

I’m going to start drawing a new path, which has nothing to do with what I drew before. Those of you who are interested in this API have noticed that many of the above examples have been used.

bezierCurveTo()

The bezier curve requires three control points, the first two city control points and the third end point. The starting point can be the last point of the current path.

/** cp1x: indicates the x-coordinate of the first control point. Cp1y: y coordinates of the first control point. Cp2x: X-axis coordinates of the second control point. Cp2y: y-coordinate of the second control point. X: the x-coordinate of the end point. Y: indicates the y-coordinate of the end point. * /
ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
Copy the code

Example:

context.beginPath();
context.moveTo(50.50);
context.bezierCurveTo(95.150.226.0.250.100);
context.stroke();
Copy the code

Effect:

clearRect()

You can set a rectangular area of the canvas to transparent

/** x: x coordinates of the upper left corner of the rectangle y coordinates of the upper left corner of the rectangle width: height: height of the rectangle */
ctx.clearRect(x, y, width, height)
Copy the code

Example:

ctx.fillStyle = '# 000'
ctx.fillRect(10.10.150.150)
ctx.clearRect(20.20.80.80)
Copy the code

Effect:

clip()

Path clipping, first draw clipping path, then draw other content in this clipping path is presented.

/** Path: Object specifies the path2D Object. Optional fillRule: This parameter is used to determine whether a point is inside or outside the path. Optional values: -nonzero non-zero surround principle, default value: -evenodd Odd surround principle. * /
ctx.clip(path, fillRule)
Copy the code

Example:

 // Draw a circle and then crop, then draw a square or draw an image
ctx.arc(100.100.50.0.20)
ctx.clip()
ctx.fillRect(0.0.200.200)
ctx.drawImage(img,0.0.300.300)
Copy the code

Effect:

closePath()

Closing a path connects the start and end positions of a path. If there is only one point, it does not take effect.

ctx.closePath()
Copy the code

Example:

ctx.beginPath()
ctx.moveTo(80.80)
ctx.lineTo(100.50)
ctx.lineTo(170.90)
ctx.closePath()
ctx.stroke();
Copy the code

Effect:

createImageData()

Create a new, blank ImageData object.

ImageData: copy an object with the same width and height. The image itself is not allowed to be copied. * /
ctx.createImageData(width, height); 
ctx.createImageData(imagedata);
// You can print it on the console.
Copy the code

createLinearGradient()

Create a linear gradient object

/** x0: y0: y0: y1: y1 */
ctx.createLinearGradient(x0, y0, x1, y1)
Copy the code

Example:

// Draw a rectangle that fades from grey to black
var gradient = ctx.createLinearGradient( 0.0.300.0)
gradient.addColorStop(0.'#CCC')
gradient.addColorStop(1.'# 000')
ctx.fillStyle = gradient
ctx.fillRect(50.50.200.100)
Copy the code

Effect:

createPattern()

Create a pattern object. The return value is a CanvasPattern object.

/** image: CanvasImageSource object as the source of the repeated image. It can be one of the following:  HTMLImageElement (), HTMLVideoElement (
      
ctx.createPattren(image, repetition)
Copy the code

Example:

var img = new Image(); 
img.src='./xx.png'
img.onload =function() {
    ctx.fillStyle = ctx.createPattern(img, null)  
    ctx.fillRect(0.0.400.400)}Copy the code

Effect:

createRadialGradient()

Determine the coordinates of two circles, drawing radioactive gradient method.

/** x0: the X-axis coordinates of the starting circle. Y0 starts with the y-coordinate of the circle. R0: radius of the starting circle. X1: the x-coordinate of the starting circle. Y1: the y coordinate of the starting circle. R1: radius of the end circle */
createRadialGradient(x0, y0, r0, x1, y1, r1)
Copy the code

Example:

let gradient = ctx.createRadialGradient(100.100.100.100.100.0)
gradient.addColorStop(0."#CCC")
gradient.addColorStop(1."# 000")
ctx.fillStyle = gradient
ctx.fillRect(0.0.200.200)
Copy the code

Effect:

drawFocusIfNeeded()

You can highlight the current path or the specified path outline if the specified element is in focus state.

/** element: Whether to set focus element path: path */
ctx.drawFocusIfNeeded(element);
ctx.drawFocusIfNeeded(path, element);
Copy the code

Example:

<canvas id='canvas' width="300" height="300">
    <button id="btn">btn</button>
</canvas>
Copy the code
BTN / /
const btn = document.getElementById('btn')
const canvas = document.getElementById('canvas')
let ctx = canvas.getContext('2d')
btn.focus()
ctx.beginPath()
ctx.rect(100.100.100.50)
ctx.drawFocusIfNeeded(btn)
Copy the code

Effect:

drawImage()

Draw an image on the Canvas.

/** img: elements drawn to context. Sx: Optional needs to draw to the target context, top left of img x-coordinate. Sy: Optionally needs to draw to the target context, the y-coordinate of the upper left corner of img. SWidth: Optional width of img's rectangle (cropped) selection box that needs to be drawn into the target context. If not stated, the entire rectangle (clipping) starts at coordinates sx and SY and ends at the bottom right corner of IMG. SHeight: The optional height of the img rectangle (clipping) selection box that needs to be drawn into the target context. Dx: the top left corner of img is the X coordinate on the target canvas. Dy: The top left corner of img is the y-coordinate on the target canvas. DWidth: Optional img The width to draw on the target canvas. Allows the img that is drawn to be scaled. If not specified, the img width is not scaled when drawing. DHeight: Optional img Height to draw on the target canvas. Allows the img that is drawn to be scaled. If not specified, the img height is not scaled when drawing. * /
ctx.drawImage(image, dx, dy);
ctx.drawImage(image, dx, dy, dWidth, dHeight);
ctx.drawImage(img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
Copy the code

Example:

<img id="myImg" src='./xx.webp'  width="300" height="227"/>
Copy the code
const myImg = document.getElementById('myImg')
ctx.drawImage(myImg,50.300.200.200.100.100.100.100)
Copy the code

Effect:

ellipse()

Draw ellipses, not supported by Internet Explorer, only supported by Edge13+.

/** x: coordinates of the center of the circle. Y: indicates the y-coordinate of the center of a circle. RadiusX: Radius of the long axis of the ellipse. RadiusY: Radius of the short axis of the ellipse. Rotation: The rotation Angle of the ellipse, expressed in radians. StartAngle: The starting point Angle to be drawn, measured in radians from the X-axis. EndAngle: The Angle at which the ellipse ends, in radians. Anticlockwise: Optional true: anticlockwise false: anticlockwise */
ctx.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise);
Copy the code

Example:

// If the long and short axes are set to the same radius, a regular ⚪ shape will appear
ctx.ellipse(150.150.200.100.45.10.45)
ctx.stroke()
Copy the code

Effect:

fill()

Path to fill

/** path: specifies the path to be filled. FillRule: specifies whether the specified point is inside or outside the path. Nonzero - Default value, evenodd */
ctx.fill(path, fillRule);
Copy the code

Example:

ctx.moveTo(80.80)
ctx.lineTo(100.120)
ctx.lineTo(20.280)
ctx.closePath()
ctx.stroke()
ctx.fill()
Copy the code

Effect:

fillRect()

Rectangle fill method.

/** x: y: y: y; width: width of the rectangle; height: height of the rectangle */
ctx.fillRect(x, y, width, height)
Copy the code

Example:

// Canvas is a king
ctx.fillRect(50.30.80.5)
ctx.fillRect(85.30.5.70)
ctx.fillRect(62.60.50.5)
ctx.fillRect(40.100.100.5)
Copy the code

Effect:

fillText()

Fill text to draw text.

/** text: indicates a text message. X: the X-axis coordinates of the starting point of the text. Y: y coordinates of the text start point. MaxWidth: Optional, the maximum width to draw */
ctx.fillText(text, x, y, [maxWidth]);
Copy the code

Example:

ctx.font = "32px SimSun";
ctx.fillText("Hello".50.100);
Copy the code

Effect:

getImageData()

Returns an ImageData object that describes the pixel data implied by the Canvas region, represented by a rectangle.

/** x: the upper-left x-coordinate of the rectangle region of the extracted image data. Y: y coordinates of the upper left corner of the rectangle region of the extracted image data. Width: The width of the extracted rectangle area. Height: The height of the extracted rectangle area. * /
ctx.getImageData(x, y, width, height)
Copy the code

Example:

// Running the HTML file locally does not take effect
const myImg = document.getElementById('myImg1')
ctx.drawImage(myImg,0.0.300.300)
​
let imgData = ctx.getImageData(50.180.100.50)
console.log(imgData);
const imgDataLength = imgData.data.length
for (var index = 0; index < imgDataLength; index += 4) {
    var r = imgData.data[index];
    var g = imgData.data[index + 1];
    var b = imgData.data[index + 2];
    var gray = r * 0.299 + g * 0.587 + b * 0.114
    console.log(gray);
    imgData.data[index] = gray;
    imgData.data[index + 1] = gray;
    imgData.data[index + 2] = gray;
}
// Update new data
ctx.putImageData(imgData, 50.184);
Copy the code

getLineDash()

Method to get the current line segment style.

// The return value is array
ctx.getLineDash();
Copy the code

getTransform()

Gets the transformation matrix currently applied to the context.

// Return value is a DOMMatrix object
ctx.getTransform();
Copy the code

isPointInPath()

Checks whether the current path contains a point

/** x: the horizontal coordinate of the point used to detect. Y: indicates the ordinate of the point used for detection. FillRule: indicates the filling rule. Used to determine whether a point is in or out of the path. Possible values include: nonzero: non-zero rule, which is the default rule. Evenodd: parity rule. Path refers to the Path2D object. * /
// The method returns a Boolean value.
ctx.isPointInPath(x, y);
ctx.isPointInPath(x, y, fillRule);
// The following syntax is not supported by IE
ctx.isPointInPath(path, x, y);
ctx.isPointInPath(path, x, y, fillRule);
Copy the code

Example:

ctx.rect(20.10.200.200);
ctx.stroke();
console.log(ctx.isPointInPath(20.10)); // true
Copy the code

isPointInStroke()

Checks if a point is on the stroke line of a path.

/** x: x coordinates of the detection point Y: y coordinates of the detection point Path: path2D path */
// Return value: Boolean
ctx.isPointInStroke(x, y);
ctx.isPointInStroke(path, x, y);
Copy the code

The sample

ctx.rect(20.10.200.200);
ctx.stroke();
console.log(ctx.isPointInStroke(20.10)); // true
Copy the code

lineTo()

Joins the current subpath point to the point specified by lineTo().

// The x and y coordinates of the parameters
ctx.lineTo(x, y);
Copy the code

Example:

// Use beginPath() to draw the starting point of the path, use moveTo() to move the brush, and use the stroke() method to actually draw the line.
ctx.beginPath();
ctx.moveTo(0.0);
ctx.lineTo(200.200);
ctx.stroke();
Copy the code

Effect:

measureText()

Measuring text information returns information contained in a TextMetrics object (such as its width).

// The parameter needs to be measured by STR
ctx.measureText(text);
Copy the code

Example:

console.log(ctx.measureText("foo"))
Copy the code

moveTo()

Represents the starting point for path drawing.

// The parameter represents the x and y coordinates
ctx.moveTo(x,y)
Copy the code

putImageData()

Method of drawing a position map of data from an existing ImageData object. If a drawn rectangle is provided, only the pixels of that rectangle are drawn. This method is not affected by the canvas transformation matrix.

/** imageData: an array object containing pixel values. Dx: The offset (X-axis offset) of the source image data in the destination canvas. Dy: The offset of the position of the source image data in the target canvas (the offset in the y direction). DirtyX: Optional position in the upper left corner of the rectangle in the source image data. The default is the upper left corner (x-coordinate) of the entire image data. DirtyY: Optional position in the upper left corner of the rectangle in the source image data. The default is the upper left corner (y-coordinate) of the entire image data. DirtyWidth: Optional width of the rectangular region in the source image data. The default is the width of the image data. DirtyHeight: Optional height of the rectangular region in the source image data. The default is the height of image data. * /
ctx.putImageData(imagedata, dx, dy);
ctx.putImageData(imagedata, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight);
Copy the code

Example:

// Start service run local file<img id="myImg1" src='./xx.webp'  width="300" height="227"/>
<img id="myImg2" src='./123.jfif' width="300" height="200" alt=""><canvas id="tutorial" width="300" height="300">Your browser does not support Canvas, please upgrade your browser.</canvas>
<canvas id="tutorial2" width="300" height="300">Your browser does not support Canvas, please upgrade your browser.</canvas>
Copy the code
const myImg1 = document.getElementById('myImg1')
const myImg2 = document.getElementById('myImg2')
ctx.drawImage(myImg2, 0.0.300.200)
const canvas2 = document.getElementById('tutorial2');
let ctx2 = canvas2.getContext('2d');
// Draw the replacement diagram
ctx2.drawImage(myImg1, 0.0.300.200)
let myImgData = ctx2.getImageData(0.0.300.200)
ctx.putImageData(myImgData, 0.0.100.50.100.100)
Copy the code

Effect:

quadraticCurveTo()

Used to draw a quadratic Bezier curve. The first point is the control point and the second is the end point. The starting point is the latest point of the current path, which can be changed using the moveTo() method.

// CPX, cpy control point x,y axis, x,y terminal coordinates
ctx.quadraticCurveTo(cpx, cpy, x, y);
Copy the code

Example:

ctx.beginPath()
ctx.moveTo(80.100)
ctx.quadraticCurveTo(150.210.280.190)
ctx.stroke()
Copy the code

Effect:

rect()

Rectangles are drawn in the same way as arc() and Ellipse (). You need to fill, you need to do fill(), and if you want to stroke, you need to do stroke(). In fact, there are ready-made methods for filling and stroke for rectangles, which are specific to rectangles: fillRect() and strokeRect().

/** x: the x coordinates of the starting point of the rectangle. Y: y coordinates of the starting point of the rectangle. Width: indicates the width of the rectangle. Height: The height of the rectangle. * /
rect(x, y, width, height)
Copy the code

Example:

ctx.rect(100.100.100.100)
ctx.stroke()
Copy the code

Effect:

restore()

State rollback. If the state is not saved, no changes are made.

ctx.restore();
Copy the code

Example:

// Save the initial state
ctx.save()
ctx.fillStyle = '#ccc'
ctx.fillRect = '100100,50,50'
// Not executing will result in two grey squares
ctx.restore()
ctx.fillRect(150.150.50.50)
Copy the code

Effect:

rotate()

Add a rotation matrix to the canvas, clockwise, in radians.

// Angle indicates the clockwise rotation of the arc. If you want to calculate by Angle value, use the formula: degree * math.pi / 180.
ctx.rotate(angle)
Copy the code

Example:

ctx.rotate(60*Math.PI / 180)
ctx.font = '24px Songti'
ctx.fillText('I am The Hammer.'.50.0)
// Reset the current transformation matrix to its initial state
ctx.setTransform(1.0.0.1.0.0);
Copy the code

Effect:

save()

Saves the current canvas state.

scale()

Scaling the canvas coordinate system only affects the coordinates, and subsequent drawing will be affected by this method. The previously drawn effect will not be changed.

/**js x: horizontal scale of canvas coordinate system. Decimals are supported, with -1 representing horizontal reversal. Y: Vertical scaling of the Canvas coordinate system. Decimal numbers are supported. -1 represents vertical reversal. */ ctx.scale(x, y)Copy the code

Example:

 ctx.fillRect(10.10.10.10);
/ / zoom
ctx.scale(10.3);
// Draw again
ctx.fillRect(10.10.10.10);
// Restore the coordinate system
ctx.setTransform(1.0.0.1.0.0);
Copy the code

Effect:

setLineDash()

Set the dotted line style.

// arr: array [dashed line implementation length, transparent part length] is a solid line if it is controlled
ctx.setLineDash(arr)
Copy the code

Example:

ctx.beginPath()
ctx.setLineDash([10.20.30.40])
ctx.moveTo(50.50)
ctx.lineTo(300.50)
ctx.stroke()
Copy the code

Effect:

setTransform()

Rewrites the current coordinate system with the identity matrix.

/** a (m11) scale horizontally. B of m12 is vertically inclined. C (M21) is tilted horizontally. D of m22 is scaled vertically. E of dx is moving horizontally. F of dy is moving vertically. * /
ctx.setTransform(a,b,c,d,e,f)
Copy the code

stroke()

Start drawing a stroke on the path.

ctx.stroke()
Copy the code

strokeRect()

Draw a rectangle.

/** x: the starting X-axis of the stroke rectangle. Y: y coordinates of the starting point of the stroke rectangle width: width height: height */
ctx.strokeRect(x, y, width, height)
Copy the code

Example:

ctx.strokeStyle = 'red'
ctx.lineWidth = 10
ctx.strokeRect(50.50.100.100)
Copy the code

Effect:

strokeText()

Achieve text stroke effect.

/** text: x */
ctx.strokeText(text,x,y)
Copy the code

Example:

ctx.font='32px Songti'
ctx.strokeText('Wang Xiaohammer'.50.50)
Copy the code

Effect:

transform()

Further transformation of the current coordinate system to achieve rotation, stretching, displacement, scaling effect.

/** a: horizontal scaling. B: Cut horizontally. C: Vertical diagonal cut. D: Vertical scaling. E: Horizontal displacement. F: Vertical displacement. * /
ctx.transform(a,b,c,d,e,f)
Copy the code

Example:

ctx.transform(1.1.0.1.0.0);
ctx.fillStyle = 'red'
ctx.fillRect(10.10.100.100);
Copy the code

Effect:

translate()

Add a translation transform to the current mesh.

/** x: the horizontal displacement distance of the coordinate system. Y: the vertical displacement of the coordinate system. * /
ctx.translate(x,y)
Copy the code

Example:

ctx.translate(50.50);
ctx.fillRect(0.0.100.100);
ctx.setTransform(1.0.0.1.0.0);
Copy the code

Praise support, hand left lingering fragrance, with rongyan, move your rich little hands yo, thank you big guy can leave your footprints.

Past wonderful recommendation

Don’t know SEO optimization? An article helps you understand how to do SEO optimization

Canvas Pit Road

Wechat small program development guide and optimization practice

Talk about mobile adaptation

Front-end performance optimization for actual combat

Talk about annoying regular expressions

Obtain file BLOB stream address to achieve the download function

Vue virtual DOM confused? This article will get you through the virtual DOM once and for all

Git Git

Easy to understand Git introduction

Git implements automatic push

How do I use Git in my work

Interview Recommendations

Front ten thousand literal classics – the foundation

Front swastika area – advanced section

More exciting details: personal homepage