This is the 8th day of my participation in the August More Text Challenge

Create a Canvas

The tag definition can be graphical, but you must use ascript (usually javascript) to draw the graph (IE9 and above supports this tag) note: By default, elements have no borders and content. You can add width and height attributes to your notes, or use style to add borders. It is recommended that you never set the CSS canvas width and height

Supported browsers render only the tags and ignore the alternative content. Browsers that do not support it render the alternative content directly. So you can add content to the tag to display when the browser does not support the Canvas tag:

<canvas> Your browser does not support Canvas, please upgrade your browser. </canvas>Copy the code

Use JavaScript to draw the image

A fixed-size canvas is created, and one or more render contexts (brushes) are exposed, which are used to draw and manipulate the content to be displayed.

Var c = document.getelementById ("mycanvas") var CTX = c.goetContext ("2d")Copy the code

Draw the shape

1. Grid and coordinate space

Canvas is covered by grid by default. A cell in the grid is equivalent to a pixel in canvas. The starting point of grid is the upper left corner and the coordinate is (0,0). All elements are positioned relative to the origin, with the positive x axis on the left and the positive Y axis on the bottom.

2. Draw a rectangle

Only one native graph drawing is supported: rectangles. All other graphs generate at least one path. Canvas provides three methods for drawing rectangles:

  • FillRect (x,y,width,height) : Draws a filled matrix
  • StrokeRect (x,y,width,height) : Draws a rectangle border
  • ClearRect (x,y,width,height) : Clears the specified rectangular region, then the region is fully transparent

Draw a path

The basic element of a graph is a path, which is a collection of points of different shapes connected by line segments or curves of different colors and widths. A path, even its subpaths, is closed. Drawing with paths requires some additional steps:

  1. Create a path start point
  2. Call the draw method to draw the path
  3. Close the path
  4. Once the path is formed, render the image by stroke or filling the area

Methods to be used:

  • BeginPath () : Creates a path. Once the path is created, the graph drawing command is directed to the path to generate the path
  • MoveTo (x,y) : Moves the brush to the specified coordinate (x,y), which is equivalent to setting the starting point of the path
  • LineTo (x,y) : Moves the brush to the specified coordinate (x,y), which is equivalent to setting the end coordinate of the path
  • ClosePath () : After the path is closed, the graph drawing command points back to the context
  • Stroke () : Draws a graphic outline using lines
  • Fill () : Generates a solid graph by filling the path content area

Draw a five-pointed star:

<canvas id="mycanvas" width="400" height="400" style="border: 1px solid red;" ></canvas> <script type="text/javascript"> var c = document.getElementById("mycanvas") var ctx = c.getContext("2d") Ctx.beginpath () ctx.moveto (120,200) ctx.lineto (200,0) ctx.lineto (300,200) ctx.lineto (80,80) ctx.lineto (320,80) CTX CTX. LineTo (120200). The stroke () < / script > < / body >Copy the code

Draw the arc

There are two ways to draw arcs:

arc(x,y,r,startAngle,endAngle,anticlockwise)

Anticlockwise is a Boolean value with (x,y) as the center and r as the radius, ending in an arc from startAngle to endAngle, with true indicating anticlockwise and false indicating clockwise (the default). You can convert angles to radians using the following code.

radians = (Math.PI/180)*degress

Note: startAngle and endAngle are radians.

Example:

var c = document.getElementById("mycanvas") var ctx = c.getContext("2d") ctx.beginPath() ctx.arc(100, 100, 100, 0, 2 * Math. PI, false); ctx.stroke();Copy the code

ArcTo (x1,y1,x1,y2,radius) draw an arc according to the specified control point and radius, and finally connect the two control points in a straight line

Example:

var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.moveTo(50, 50); ArcTo (200, 50, 200, 200, 100); CTX. ArcTo (200, 50, 200, 200, 100); ctx.lineTo(200, 200) ctx.stroke();Copy the code

The way to think about it is this. The arc drawn is determined by two tangent lines. Tangent line 1: the line determined by the starting point and control point 1. Second tangent: the straight line determined by control point 1 and control point 2. In fact, the arc drawn is the arc tangent to these two lines.

Add styles and colors

Color the figure

FillStyle = color: set the fill color of the graph. StrokeStyle = color: set the color of the outline of the graph. Once set, this new value will become the default value of the newly drawn graph

Transparency

GlobalAlpha = transparencyValue: This property affects the transparency of all graphics in the Canvas and is valid for 0-1

Line style

Line width (positive value only)

ctx.lineWidth = 10

lineCap = type

Optional value:

  • Butt: The line segment ends in a square
  • Round: A line segment ends in a circle
  • Square: The end of a 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

lineJoin = type

Optional value:

  • Round: Draw the shape of the corner by filling an extra sector with a center at the end of the connected section. The radius of the corner is the width of the segment.
  • Bevel: Fill the ends of the connected sections with an additional triangular base area, each with its own separate rectangular corner.
  • Miter :(default) by extending the outer edges of the connected sections so that they intersect at a point, forming an additional rhomboid area.

Added style to pentacle:

<body> <canvas id="mycanvas" width="400" height="400" style="border: 1px solid red;" ></canvas> <script type="text/javascript"> var c = document.getElementById("mycanvas") var ctx = c.getContext("2d") Ctx.beginpath () ctx.moveto (120,200) ctx.lineto (200,0) ctx.lineto (300,200) ctx.lineto (80,80) ctx.lineto (320,80) ctx.closePath() ctx.lineWidth = 20 ctx.lineCap = "butt" ctx.stroke() </script> </body>Copy the code

Dotted line

Use the setLineDash method and the lineDashOffset attribute to specify the dotted line style.

  • SetLineDash () takes an array [solid line length, gap length] to specify line segment and gap alternation
  • The lineDashOffset property sets the starting offset
  • GetLineDash () returns an array containing the current dotted line style and a non-negative even length

Draw text

  • FillText (text,x,y) : Fills the specified text at the specified (x,y) position. The maximum width of the drawing can be set
  • StrokeText (text,x,y) : Draws a text border at the specified (x,y) position. The maximum width can be set

Add styles to text

  • Font = value: The style we currently use to draw text. This string uses the same syntax as the CSS font property. The default font is 10px sans-serif.
  • TextAlign = value: Text alignment option. Possible values are start, end, left, right, or Center. The default value is start.
  • TextBaseline = value: baseline alignment options. Optional values include top, Hanging, middle, alphabetic, ideographic, and bottom. The default value is alphabetic.
  • Direction = value: indicates the text direction. Possible values include: LTR, RTL, inherit. The default value is inherit.

Draw pictures

Create the image starting from 0

var img = new Image()
img.src = "myimg.png"
Copy the code

Draw the img

Ctx. drawImage(img,0,0) parameter 1: the img parameter to draw 2 and 3: the coordinates in the canvasCopy the code

Note: Considering that the image is loaded from the network, the browser will throw an exception if the image is not loaded before the drawImage is completed. We need to ensure that the image is drawn after the IMG is completed.

var img = new Image(); Img. onload = function(){ctx.drawImage(img, 0, 0)} img. SRC = 'myimage.png '; // Set the image source addressCopy the code

Zoom pictures

DrawImage () can also be used to add two parameters: width and height to scale the image

State preservation and recovery

When painting, there will often be such a situation, originally with a green pen, suddenly need to use a red pen to draw a few strokes, but after finishing the painting to change to a green pen. If you’re drawing in real life, dip your pen in different inks and then use the same ink as before, or have several pens and use whichever one you want.

This can also be done in Canvas, but there is only one brush in Canvas. So, if you want to change the color of the brush, you need to save and restore the state. The state is simply a snapshot of the canvas’s current properties.

The Save() and restore() methods: used to Save and restore the canvas state, have no arguments.

1. About Save () : The Canvas state is stored in the stack. Whenever save() is called, the current state is pushed to the stack for saving. The save method (array-like push()) can be called any number of times. The save method (array-like push()) can be called any number of times. 2. About restore() : Each time the restore method is called, the last saved state is popped from the stack and all Settings are restored (array-like pop()).

Example:

<body> <canvas id="mycanvas" width="400" height="400" style="border: 1px solid red;" ></canvas> <script type="text/javascript"> var ctx; function draw(){ var canvas = document.getElementById('mycanvas'); if (! canvas.getContext) return; var ctx = canvas.getContext("2d"); ctx.fillRect(0, 0, 150, 150); Ctx.save () ctx.fillstyle = 'red' // Change the color of ctx.fillrect (15, 15, 120, 120) based on the previous configuration; // Draw a rectangle ctx.save() with the new Settings; Ctx. fillRect(30, 30, 90, 90); 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 with the loaded configuration} draw(); </script> </body>Copy the code