Effect of the project

In feature

Canvas:

  • Skeleton template
  • Basic attributes
    • getContext()
    • strokeStyle
    • fillStyle
    • fillRect
    • lineCap
    • lineJoin
  • The path to draw
    • beginPath()
    • lineTo()
    • moveTo()

Mouse event handling:

  • mousemove
  • mousedown
  • mouseup
  • mouseout

Process guidance

  1. Get the<canvas>Element and set the width and height
  2. .getContext('2d')Gets the context, represented below as CTX
  3. Set CTX basic properties
    • Stroke and line colors
    • Line width
    • Line end shape
  4. Painting effect
    1. Sets a variable that marks the state of the painting
    2. Mouse event listener, different types of events will mark variable set to different values
    3. Write the function triggered when drawing, set the starting point and end point of the drawing path
  5. Line rainbow gradient effect (using HSLhChange in value, summation)
  6. Line thickness Gradient effect (Set a range beyond which the line thickness changes in reverse

Canvas related knowledge

Canvas_API

A quick introduction to HelloWorld

First, template skeleton

<! DOCTYPE html><html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Canvas realizes rainbow brush painting board</title>
  <style type="text/css">
    canvas {
      border: 1px solid black;
    }
  </style>
</head>

<body>
  <canvas id="canvas" width="150" height="150"></canvas>
  < script></ script>
</body>

</html>
Copy the code
  • The < canvas > element
<canvas id="canvas" width="150" height="150"></canvas>
Copy the code

Canvas looks a lot like the IMG element, except that it doesn’t have SRC and Alt attributes. In fact, the Canvas tag has only two attributes — width and height. These are optional and are also set using DOM properties. When the width and height are not set, the canvas initializes 300 pixels wide and 150 pixels high. The element can be sized using CSS, but when drawn the image will scale to fit its frame size: if the CSS size is not proportional to the original canvas, it will distort.

  • The rendering context
var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');
Copy the code

The Canvas element creates a fixed-size canvas that exposes one or more render contexts that can be used to draw and process the content to be displayed.

The canvas is initially blank. To display, the script first needs to find the render context and then draw on top of it. The Canvas element has a method called getContext(), which is used to get the rendering context and its drawing function. GetContext () has only one argument, the format of the context. For 2D images, basic tutorial, you can use CanvasRenderingContext2D

Project source code analysis

The source code

<! DOCTYPE html><html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Achieve rainbow brush painting board 😊</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    canvas {
      border: 1px solid black;
    }
  </style>
</head>

<body>
  <canvas id="canvas" width="1200" height="800"></canvas>< script type="text/javascript"> // get canvas node let canvas = document.querySelector('#canvas'); let ctx = canvas.getContext("2d"); let colorDeg = 0; let lineWidth = 50; let direction = true; StrokeStyle = 'HSL (${colorDeg}, 90%, 50%)'; // Ctx. strokeStyle = 'HSL (${colorDeg}, 90%, 50%)'; ctx.lineWidth = `${lineWidth}`; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; let drawing = false; let [x, y] = [0, 0] function draw(e) { if (! drawing) return; ctx.beginPath(); ColorDeg = colorDeg < 360? colorDeg + 1 : 0; if (lineWidth > 50 || lineWidth < 10) { direction = ! direction } direction ? lineWidth++ : lineWidth--; ctx.lineWidth = `${lineWidth}`; // ctx.strokeStyle = 'HSL (${deg}, 90%, 50%)'; // Control the drawing path ctx.moveto (x, y); console.log(x, y); ctx.lineTo(e.offsetX, e.offsetY); [x, y] = [e.offsetX, e.offsetY]; ctx.stroke(); } canvas.addEventListener("mousedown", (e) => { drawing = true; [x, y] = [e.offsetx, e.offty]}); canvas.addEventListener('mousemove', draw) canvas.addEventListener('mouseup', () => { drawing = false }); canvas.addEventListener('mouseleave', () => { drawing = false }) </ script></body>

</html>
Copy the code

Source code analysis

Canvas

attribute

  • lineCap: the shape of the brush strokes, round | butt |, square, round, flat, square of three.
  • lineJoin: the style of the line intersection, round | bevel | miter, oblique, miter three round.
  • lineWidth: Width of a line
  • strokeStyle: Line stroke color
  • fillStyle: Fill color

methods

  • beginPath(): Creates a path
  • stroke(): Draw the outline
  • moveTo()The starting point of the drawing operation
  • lineTo(): Indicates the end of a path

Rainbow gradient color — HSL

In this challenge, which involves changing the color of the line, how do you achieve the gradient effect of the rainbow? We need to use HSL color mode. First, we can go to mothereffinghsl.com to feel the effect of different HSL color values.

  • H(Hue) indicates the hue. The value ranges from 0 to 360
  • S is saturation, which can be understood as the gray value doped in, and its value is 0~1
  • L is brightness, which is also 0 to 1, or percentage.

The change of H value from 0 to 360 represents the value range change of hue Angle, which can be used to achieve the gradual change of line color when drawing, just need to restore to 0 and add again when its value exceeds 360.

let colorDeg = 0;

ctx.strokeStyle = `hsl(${ colorDeg }`, 90%, 50%);	
colorDeg = colorDeg < 360 ? colorDeg + 1 : 0;
Copy the code

In addition, if you want to achieve the color of black and white ink, you can set the color to black, through the change of transparency to achieve different shades of color.

Control stroke size

 // Control the stroke size
      if (lineWidth > 50 || lineWidth < 10) { direction = ! direction } direction ? lineWidth++ : lineWidth--; ctx.lineWidth =`${lineWidth}`;
Copy the code

In the above code, the value of direction is controlled according to the change of the width of the line, and the value of direction is controlled to increase or decrease the line width.

Control line path

      // Control the drawing path
      ctx.beginPath();
      ctx.moveTo(x, y);
      console.log(x, y);
      ctx.lineTo(e.offsetX, e.offsetY);
      [x, y] = [e.offsetX, e.offsetY];
      ctx.stroke();
Copy the code

Event listening code logic analysis

canvas.addEventListener('mousedown'.(e) = > {
// Start drawing
 drawing = true;
// Start drawing coordinates initialized
 [x, y] = [e.offsetX, e.offsetY]
});

// Call draw when the mouse moves
canvas.addEventListener('mousemove', draw);
// Set Drawing to false when the mouse is lifted
canvas.addEventListener('mouseup'.() = > drawing = false);
// Set Drawing to false when the mouse is not within the drawable area
canvas.addEventListener('mouseout'.() = > drawing = false);
Copy the code