Introduction to the

Canvas is newly added in HTML5, and it uses javaScript to draw the graph beginPath() to create the path, closePath() to close the path, Arc (x, y, r, startAngle, endAngle, Anticlockwise) draws an arc, stroke() draws, moves the brush moveTo(x,y) start coordinates, and lineTo(x,y) halfway coordinates

First, create a canvas container

html

<canvas id="ctx" style="border:1px solid #000;" width="600" height="600">
</canvas>
Copy the code

js

getDom(domId){
    return document.querySelector(domId)
}
let canvas = getDom('#ctx')
let ctx = canvas.getContext('2d')
Copy the code

With this introduction to artboard creation, let’s move on to our code for drawing polygons

js

Building a class

Let start = new Draw('# CTX ') class Draw(){constructor(domId){// this. DomId = domId This.datalist =[] this.ischange = false this.changeFatherIndex = 0}}Copy the code

Access to the dom

GetDom (){//this.domId is stored in the constructor let canvas = document.querySelector(this.domId) let CTX = Canvas.getContent ('2d') Let BTN = document.querySelector(this.btnId) return {canvas, CTX, BTN}}Copy the code

Register mouse events

The event () {/ / mouse press event, click the start method is used to record the coordinates of the point in the document in the dataList. AddEventListener (' mousedown 'this. Start. Bind (this)) / / open change pattern in the endpoint using the document. The addEventListener (" mouseup ", enclosing closeChange. Bind (this)) document. The addEventListener (" mousemove ", Btn.addeventlistener ('click', this.end.bind(this))}Copy the code

drawing

(Redraw the graph every time the data changes) because there is an endpoint drag requirement behind it

draw(){ let { canvas, } = this.getdom () let CTX = canvas. GetContext ("2d")} = this.getdom () let CTX = canvas. GetContext ("2d" ForEach ((item, I) => {item.forEach((itemi, indexi) => {// if indexi! If == 0 is not the starting point, so I'm going to go straight down, but if it's the starting point, I'm going to create the path. If (indexi! == 0) { ctx.arc(itemi.x, itemi.y, 1, 0, 2 * Math.PI); Ctx.lineto (itemi.x, Itemi.y) if (indexi == item.length-1 && this.ischange) {ctx.closepath ()} ctx.stroke()} else {// Close a graph if if not the first one  (i > 0) { ctx.closePath() ctx.stroke() ctx.beginPath() } else { ctx.beginPath() } ctx.arc(itemi.x, itemi.y, 1, 0, 2 * Math.PI); ctx.stroke() ctx.moveTo(itemi.x, itemi.y) } }) }) }Copy the code

Record the coordinates

start(e) { let { canvas, } = this.getdom () // mouse x y position let x = e.pagex - canvas. OffsetLeft let y = e.pagey - canvas If (this.datalist. Length == 0) {if (this.datalist. Length == 0) { This.datalist = [[]]} if (y > e.ffsetx &&x < bodyy&&x > e.ffsetx &&x < bodyX) {this.datalist = [[]]} if (y > e.ffsetx &&x < bodyX) { // The searchData method is used to change the drawing mode when clicking on an endpoint. Y)) {this.ischange = true} else {this.datalist [this.datalist. Length - 1]. y }) this.fatherIndex = this.dataList.length - 1 this.draw() } } }Copy the code

Checks whether it is an endpoint

searchData(x, y) { let flag = false this.dataList.forEach((item, index) => { item.forEach((data, If (data.x > x-3&&data.x < x + 3&&data.y > y-3&&data.y < y + 3) {// if (data.x > x-3&&data.x < x + 3&&data.y < y + 3) {// If (data.x > x-3&&data.y < y + 3) { this.changeFatherIndex = index this.changeIndex = i flag = true } }) }) return flag }Copy the code

Close graph – Finish selection

end() { let { canvas, } = this.getdom () let CTX = canvas.getContext("2d") ctx.closepath () ctx.stroke() ctx.beginPath() // Create the next shape this.dataList.push([]) }Copy the code

Change the endpoint

ChangeData (e) {if (this.ischange) {this.close() let {canvas, } = this.getdom () let x = e.pagex - canvas.offsetLeft let y = e.pagey - canvas.offsetTop canvas.offsetWidth let bodyY = e.pageY + canvas.offsetHeight if (y > e.offsetY && y < bodyY && x > e.offsetX && x < This.datalist [this.changefatherIndex][this.changeIndex] = {x, y} // redraw this.draw()}}Copy the code

Click Finish to select the closed shape

closeChange() {
    this.isChange = false
}
Copy the code

html

<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <title> Canvas polygon </title> </head> <body> <div> <button ID =" BTN "> Complete selection </button> </div> <canvas ID =" CTX"  style="border:1px solid #000;" width="600" height="600"> </canvas> </body> </html>Copy the code

conclusion

I would like to share my thoughts on drawing polygons. First of all, I need to create a drawing board. When clicking the mouse for the first time, I need to create a starting point.

Drag the endpoint to change the endpoint position, above we first draw each graph (x, Y) coordinates to save in an array, mouse click on the endpoint to save the endpoint position, mouse lift the current drag endpoint (x, Y) coordinates change, to empty the drawing board and beginTo() a new graph

In the process of writing the project, I often write a lot of repeated code, which is not very reusable. This time, I tried to use the object-oriented programming mode, and I felt many benefits in the process of using it. The most important thing is that the code will be more readable, and it can be easily identified when finding bugs.