Preface:

This project uses 75% of canvas API, which seems to be a lot, but actually it is not much.

This article is suitable for those who have a certain canvas foundation.

This article will take you through the project from four points:

  1. Project introduction

  2. Project Effect Display

  3. Description of project development process and variables

  4. Difficulties and solutions encountered in the project

1. Project introduction

Project name: Get to the bowl – Sketchpad

Completed functions:

  1. painting
  2. Draw a straight line
  3. screenshots
  4. Screenshot of rotating
  5. barrage
  6. Mouse touch bullet screen, bullet screen hover
  7. Undo/advance
  8. Design brush information
  9. Compatible mobile terminal

2. Project effect display

Project address Preview address

preview



UI design is a reference: hand by hand to teach you to implement a Canvas wise drawing board

Really feel the interface design is good, I borrowed from it, ha ha ha. But my DOM architecture design is different from the one in the article above.

3. Description of project development process and variables

Front that


If you need to learn and reference code, you need to look here. Because of the complex functions, there are nearly 10 variables in the logo, which may be difficult to understand at a moment. Therefore, I will explain my development process and the sequence of defining variables here.Copy the code
  1. Function sequence:

Brush → Define Brush information → Eraser → Delete → Undo/Forward → Straight line → Screenshot → bullet screen

  1. Define the order of variables and what they do:

All functional variables:

var isDown = false                  // flag whether the mouse presses drawing step 3 and cutting step 3, the following two events trigger the flag
var points = []                     // In order to make the line smooth, record the points and shorten the distance of the drawing line
var beginPoint = null               // The starting point is used when drawing three steps---- These three as a group, draw the line trio, in order to make the line drawn more smoothvar currentMenu = "icon-pen"        // Start button bottom button Selected button
var currentColor = 0                // Select the index color of the initial color, default first
var paintingModal = "pen"           / / brush model line | | pen | | the cut---- button function trio, button select mark, color select, drawing mode, switch front brush and drawing straight line modevar lookModal = false               // The first function of the mouse mode button, this mode can not draw, only look
var cuted = false                   // Whether the clipping mark has been clipped to prevent subsequent operations from triggering the clipping operation again---- Definition of mouse mode and clipping modevar animationTimer = null           // The timer of the barrage animation
var barrageArray = []               // Save the array of bullets
var globalPoint = { x : 0.y : 0 }  // Canvas mouse point -- used for barrage---- Bullet-screen trio globalPoint is used to mark the coordinates of the mouse in the canvas to determine whether the mouse touches the bullet-screen// Implement undo and redo functions
let canvasHistory = []                    // Canvas data, save data after each drawing and eraser use
let step = 0                              // The number of steps raised by the brush is cleared as well---- Undo/Advance duo. When the brush is lifted, the canvas information is stored in canvasHistory with getImageData, and the forward and undo functions are completed with stepvar penAttibutes = {                       // Brush data,
    width : 2.lineCap : "round".lineJoin : "round".strokeStyle: "# 000".fillStyle: "# 000".globalCompositeOperation: "source-over".globalAlpha : 1
}

Copy the code

4. Difficulties and key points encountered in development and solutions:

1. Save historical records and use API comparison

I have done when writing code to reference * * [taught you how to implement a wisdom of canvas painting board] (https://juejin.cn/post/6844903788998836231) * *, used in the article is canvas. ToDataUrl way to do data save, The comments say that the data storage is not ideal, in fact, I originally thought to use ctx.getImageDaata to do the way, I also use the two API to do a comparison:Copy the code

Code:

Results:


It can be seen that it takes a very short time to obtain data using getImageData, and the pixel data of the canvas can be obtained. Subsequent pixel operations can be carried out directly, so that no longer need to spend time to obtain the canvas information. Secondly, the data obtained by getImageData has data structure. Saving data in memory is more memory friendly, whereas saving data in toDataUrl with 210,000 lines of strings is not memory friendly. Later, I also compared the time that they drew on the canvas, and their time was within 1ms. Each time, putImageData was a little faster, but the faster time did not mean much. ToDataUrl is also beneficial because the transpose is a Base64 string, so it can be used directly as the SRC attribute for the image to be displayed on the page.Copy the code

2. Draw a straight line

How w do I draw a straight line? So when I do undo and Forward, I save the artboard data into canvasHistory, which is exactly what I'm going to use here, when I move the mouse, I'm going to clear the canvas, and then I'm going to draw the last data that I saved in canvasHistory, and then I'm going to draw in three steps, and I'm done. ** Note: ** here must be drawing three steps, or before drawing must use beginPath() to reopen a path, if you do not reopen the path, when drawing, the front line will be drawn together, because you have been a path, so the next drawing, the last point also want to draw again.Copy the code

3. Picture rotation

Rotation is similar to CSS3, but the canvas base is fixed at the top left corner, so when rotating, move the canvas with Translate.Copy the code

Here’s what I drew:

The current operation of putImageData will not succeed when the pen has the rotate propertyCopy the code

4. How to draw a smooth curve

When using normal drawing method to draw curves, the curves drawn are not smooth enough, so I refer to this article **[Canvas Advanced - how to draw a smooth curve? (https://segmentfault.com/a/1190000016672567) * * (actually I also thought of using quadratic bezier curves, when looking for a better solution, to find the way, this scheme is better), the principle, we can see the original.Copy the code

5. Touch the bullet screen with the mouse

Since canvas is memoryless, when you use isPointPath and isPointStroke, you can only detect it under the current painting. When using isPointPath, it is only associated with path paths, meaning that you cannot detect a rectangle drawn directly with fillRect, but only within paths bounded by rect() and pathTo. So, here I made a plugin path - enclose each barrage with rect() ------ haha -Copy the code

6. Use drawImage:

There are three ways to pass a drawImage, and the effects generated by the three ways can be referred to before writing.Copy the code

Reference address: CanvasRenderingContext2D drawImage

7. Compatible with mobile terminals

When on the mobile terminal, there will be a delay of 300ms on the mobile terminal, because the mobile terminal has the double click amplification function, so there will be 300ms time. My solution was to set the meta information and forbid zooming to prevent the 300ms problemCopy the code
    <meta name="viewport" content="Width =device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi" />
Copy the code

Conclusion:

First of all, thank you very much for the author’s sharing of a Canvas Wisdom drawing board. I also referred to the author’s interface design. I hope the author doesn’t mind.

Secondly, this project uses about 75% of canvas’S API, and there is still no use of the gradient API. Although pixels are obtained, they are not operated on.

Finally, I hope this article is helpful to you.

With you!

Reference Materials:

  • Hand in hand to teach you to achieve a Canvas wise painting board

Reference the style of the main project, but all the styles are written by myself, hee hee, the way to achieve different oh.

  • Canvas Advanced – How to draw a smooth curve?

Let me draw a smooth curve. Nice.

  • Canvas animation teaches, not teaches

Here you can write down the meaning and function of all apis, parameters, etc —–

  • Canvas API Chinese document home page map

All canvas apis, of course, you can also go to MDN, in fact, are the same