Canvas - Day2, Simple Graphics

1. Rectangle

There are three types of rectangles:

  • Outline, draw four sides.
  • To fill, draw a rectangular area.
  • Clear to make a rectangular area completely transparent.

Example:
fill with green.
Clear a slice.
Outline red.

pen.fillStyle = 'green';
pen.fillRect(0, 0, 300, 300);

pen.clearRect(50, 50, 200, 200);

pen.strokeStyle = 'red';
pen.strokeRect(100, 100, 100, 100);

Effect:

insert image description here

2. Path

The basic process of drawing a path:

  1. Open path, beginPath()
  2. One-pass operation
  3. Close path, closePath()
  4. Select, outline or fill. stroke(), fill()

PS: The filled path will be closed automatically.
You can also manually animate to the closed point to close.

Example: Triangle

pen.beginPath();
pen.moveTo(150, 0);
pen.lineTo(0, 150);
pen.lineTo(150, 300);
pen.fill();

pen.beginPath();
pen.moveTo(300, 0);
pen.lineTo(150, 150);
pen.lineTo(300, 300);
pen.closePath();
pen.stroke();

insert image description here

move

moveTo(x, y)

straight line

lineTo(x, y)

arc

arc(x, y, radius, startAngle, endAngle, anticlockwise)
center, radius, start angle, end angle.
Optional, whether to counterclockwise. Default false clockwise.

pen.beginPath();
pen.arc(150, 150, 150, 0, Math.PI)
pen.fill();

Effect: 0 to π clockwise.

insert image description here

arcTo(x1, y1, x2, y2, radius)
is more complicated, and the arc is determined by two points and one corner.

There are three points:
starting point M,
A, x1y1
B. x2y2

a radius.

MA and AB, the intersection of the vertical lines is the center of the circle. radius.

pen.beginPath();
pen.moveTo(0, 0)
pen.arcTo(300, 0, 300, 300, 300)
pen.stroke();

Effect:

insert image description here
Insufficient radius will:

insert image description here

Bessel

quadraticCurveTo(cp1x, cp1y, x, y)
One control point, one end point.

pen.beginPath();
pen.moveTo(0, 0)
pen.quadraticCurveTo(300, 0, 300, 300)
pen.stroke();

Effect:

insert image description here

bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
two control points, one end point.

pen.beginPath();
pen.moveTo(0, 0)
pen.bezierCurveTo(300, 0, 300, 300, 0, 300)
pen.stroke();

Effect:

insert image description here

There is also a starting point.

rectangle

rect(x, y, width, height)
walks around and returns to the original starting point.

pen.beginPath();
pen.rect(50, 50, 200, 200)
pen.fill();

Effect:

insert image description here

3 , Path2D

Born for reuse. All path operations can be used on it.
It doesn't need to be turned on and it doesn't need to be turned off.

Simple to use:

function draw(pen) {
    
    
	let a=new Path2D();
	a.rect(50, 50, 200, 200)
	pen.fill(a);
}

Effect:

insert image description here

Guess you like

Origin blog.csdn.net/qq_37284843/article/details/123683455