preface
From the very beginning, Xiaobai has made many mistakes with canvas and accumulated some good ideas. This episode also makes some arrangement of Canvas API for himself and points needing attention
Refer to the website
MDN
The article links
Wechat H5 realizes webpage long press to save pictures and recognize TWO-DIMENSIONAL code (Canvas conversion)
—- Canvas Implements artboard and custom brushes (brush mismatch, retract, thickness, color)
Front-end learning notes —- Multiple pictures generate canvas ideas
Alternative content
In older browsers that do not support Canvas (especially IE before Internet Explorer 9), canvas is replaced by the contents of the tag (which can be used to indicate that canvas is not compatible)
<canvas width="150" height="150"> This browser is not compatible with canvas </canvas> <canvas width="150" height="150">
<img src="images/clock.png" width="150" height="150" alt=""/>
</canvas>
Copy the code
Render context getContext(‘2d’)
Get the rendering context and its drawing capabilities. For example, all the operations used to define brush styles and draw. GetContext () has only one argument
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d'); // CTX is the context of the tag id canvasCopy the code
Canvas Grid
Canvas Canvas is actually like a coordinate system, and it is drawn on the drawing board using the built-in Api. Generally speaking, a unit of coordinate is equivalent to a pixel of Canvas. The grid is like a coordinate system, but it starts from the upper left corner, and you can use the coordinate system to draw
Note: it is best not to use style or class to define the length and width of canvas. The small cells in the canvas will be compressed or stretched by style and other styles, so that your painting will be distorted
So what to do
<canvas id="canvas" width="200" height="200"Var canvas = document.getelementById ('canvas');
var ctx = canvas.getContext('2d');
ctx.width = 200
ctx.height = 200
Copy the code
graphics
Draw a rectangle
Canvas generates graph according to path. Canvas only supports one kind of native graph drawing: rectangle. Without path drawing, it is possible to draw various graph
StrokeRect (x, y, width, height) // Draw the border of a rectangle clearRect(x, y, width, height) Height) // Clear the specified rectangle so that the clear part is completely transparent.Copy the code
X and y specify the coordinates of the upper-left corner (relative to the origin) of the rectangle drawn on the Canvas canvas. Width and height set the size of the rectangle.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d'); ctx.fillRect(25, 25, 100, 100); ctx.clearRect(45, 45, 60, 60); Ctx. strokeRect(150, 50, 50, 50);Copy the code
Draw the path
The combination of paths allows you to draw anything you want, just like you draw on a piece of paper
BeginPath () // Create a new path. After the path is created, the graph drawing command is pointed to the path to create the path. ClosePath (); // Close the path and the draw command will point back to the context. // Not every time you need a closePath to finish drawing, you don't need a right Angle after two strokes, but you want to draw a closed direct triangle. Using this interface, you can automatically connect the end and air cushion to stroke() // Draw the outline of the graph with lines. Fill () // Generates solid shapes by filling the content area of the path.Copy the code
closePath()
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d"); ctx.beginPath(); CTX. MoveTo (20, 20); CTX. LineTo (20100); CTX. LineTo (70100); ctx.stroke();Copy the code
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d"); ctx.beginPath(); CTX. MoveTo (20, 20); CTX. LineTo (20100); CTX. LineTo (70100); ctx.closePath(); ctx.stroke();Copy the code
moveTo(x,y)
Where to start
At which point do you press the tip of your pencil onto the drawing board
You can also use moveTo to draw discontinuous points
lineTo(x,y)
Draws a line from the current position to the specified x and y positions.
The start point is related to the previous drawing path, the end point of the previous drawing path is the start point of the next drawing path, etc… The starting point can also be changed by the moveTo() function.
The circular arc
arc(x, y, radius, startAngle, endAngle, anticlockwise)`
Draw a radius arc (circle) with (x,y) as the center, starting with startAngle and ending with endAngle, in the direction given by anticlockwise (clockwise by default).
X,y are the coordinates of the center of the circle on which the arc is drawn. Radius indicates the radius. The startAngle and endAngle parameters define the starting and ending radians in radians. All of these are based on the X-axis. The anticlockwise parameter is a Boolean value. True, counterclockwise, otherwise clockwise.
Note: The unit of Angle in the arc() function is radians. Js expression for Angle and radian: Radian =(math.pi /180)/ Angle
arcTo(x1, y1, x2, y2, radius)
Draw an arc according to the given control point and radius, and then connect the two control points in a straight line.
rectangular
rect(x.y.width.height)
Draw a rectangle with upper-left coordinates (x,y), width and height.
coloring
fillStyle = color
Sets the fill color of the graph.
strokeStyle = color
Sets the color of the graphic outline.
var ctx = document.getElementById('canvas').getContext('2d');
for(var i=0; i<6; i++){for(var j=0; j<6; j++){ ctx.fillStyle ='rgb('+ math.h floor (255-42.5 * I) +', '+ math.h floor (255-42.5 * j) +', 0) '; CTX. FillRect (25, j * I * 25,25,25); }}Copy the code
Other Line apis
LineWidth = value // set the lineWidth. lineCap =type// Set the end of the line style. lineJoin =type// Set the style of the line and the indirect line. MiterLimit = value // Limit the maximum length at which two lines intersect; The so-called intersection length (miter length) is the length from the inner corner to the outer corner of the line where it meets. GetLineDash () // Returns an array containing the current dashed line style and a non-negative even length.setLineDash(segments) // Sets the current dashed line style. LineDashOffset = value // Sets the starting offset of the dashed line style.Copy the code
LineWidth = value lineWidth.
LineCap = type End of line style.
Type == butt, round, squareCopy the code
Note: If you use butt to draw the path with the mouse, it will lead to more corners at the beginning and end. Use round to achieve a better visual effect
LineJoin = type The style of the line where the line meets the line.
type= round, bevel, miter The default is miter.Copy the code
Note: As above, using the default value will result in a lot of edges and corners. Use round to achieve better visual effect
Dotted line
The setLineDash method and the lineDashOffset property specify the dashed line style. The lineDashOffset property sets the starting offset.
var ctx = document.getElementById('canvas').getContext('2d');
var offset = 0;
function draw() {ctx.clearrect (0,0, canvas.width, canvas.height); ctx.setLineDash([4, 2]); ctx.lineDashOffset = -offset; CTX. StrokeRect (10, 10, 100, 100); }function march() {
offset++;
if (offset > 16) {
offset = 0;
}
draw();
setTimeout(march, 20);
}
march();
Copy the code
image
Canvas can also draw existing pictures on the artboard for editing
var img = new Image(); // Create an img img.src ='xxx.png'; // Set the image addressCopy the code
Note: if you want to draw pictures to canvas by SRC, you must use img.onload and wait for img. SRC to finish loading before rendering to canvas, otherwise you may render blank
var img = new Image(); // Create an img object img.onload =function(){// execute the drawImage statement} img.src ='myImage.png'; // Set the image addressCopy the code
draw
drawImage(image, x, y)
Image is the img object above or the Canvas object x and y are its starting coordinates in the target canvas canvas.
Zoom Scaling
drawImage(image, x, y, width, height)
This method has two additional arguments: width and height, which control how much to scale when drawing to the canvas
slice
Use slicing if you only need to use parts of an image
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
The first parameter is the same as the others. The other 8 parameters are best referred to the diagram on the right. The first 4 parameters define the slice position and size of the image source, and the last 4 parameters define the target display position and size of the slice.
save() remote()
How does two SAO operation mean
To put the configured styles into a stack again and again, you need to take things out of the stack like a palindrome “12344321”
function draw() {
var ctx = document.getElementById('canvas').getContext('2d'); ,0,150,150 CTX. FillRect (0); // Draw a rectangle ctx.save() with default Settings; // Save the default state ctx.fillstyle ='#09F'Ctx.fillrect (15,15,120,120); ctx.fillrect (15,15,120); // Draw a rectangle ctx.save() with the new Settings; // Save the current state ctx.fillstyle ='#FFF'// Change the color configuration ctx.globalalpha = 0.5 again; CTX. FillRect (30,30,90,90); // Draw a rectangle ctx.restore() with the new configuration; // reload the previous color state ctx.fillrect (45,45,60,60); // Draw a rectangle ctx.restore() using the previous configuration; // load the default color configuration ctx.fillrect (60,60,30,30); // Draw a rectangle using the loaded configuration}Copy the code
mobiletranslate
translate(x, y)
Copy the code
The Translate method takes two arguments. X is the left/right offset and y is the up/down offset, as shown on the right.
Rotate the Rotating
rotate(angle)
Copy the code
This method takes only one parameter: Angle, which is a clockwise value in radians.
Zoom Scaling
scale(x, y)
Note: the default grid is one pixel per unit and is scaled at the unit level by scale, with the same unit for each image
The scale method takes two parameters. X and y are scaling factors for the horizontal and vertical axes, respectively, and they must both be positive. A value less than 1.0 indicates shrinking, a value greater than 1.0 indicates magnification, and a value of 1.0 has no effect.