In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge of this article "how to add events in html5", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to add events in html5" article.
In a stupid way.
We all know that when an element triggers an event, its mouse position is basically over the element, so we naturally think of comparing the current mouse position with the position occupied by the object. so we can figure out whether the object should trigger the event. This approach is relatively simple, so I don't need to demonstrate it in code, but since I call it a silly way, it's obviously not an effective solution. Because the position occupied by an object is not necessarily very easy to obtain, if it is a rectangle, a circle, etc., we can still obtain its position through some simple formulas, but in complex polygons, even some sides of the polygon are curved, it is obvious that it is extremely complex and difficult for us to obtain the position it occupies at this time. So this method is only suitable for you to use in doing some demo, and not suitable for most situations.
A smarter way
Now that we have hit a brick wall in this way, we can only find another way. When flipping through CanvasAPI, we found a way to isPointInPath, which seems to be the good medicine we are looking for.
Introduction to isPointInPath
The role of isPointInPath: as the name implies, we can intuitively know that this method is used to determine whether the point is in the path.
The input and output parameters of isPointInPath: ctx.isPointInPath ([path,] x, y [, fillRule]). There are 4 parameters for this method, of which path and fillRule are optional and x and y are required. We introduce four parameters in turn.
Path: when I saw this parameter, I at first thought it was the return value of beginPath or closePath. Unfortunately, these two methods did not return a value. After looking up the data, I found that it was the object of the Path3D constructor new. The specific usage of the Path3D constructor. However, it is a pity that this method may be due to compatibility problems, so some open source frameworks have not been used yet.
XQuery y: these two parameters are easy to understand, that is, the distance between the x axis and the y axis, and it should be noted that their relative position is the upper left corner of the Canvas.
FillRule:nonzero (default), evenodd. The non-zero orbit rule and the parity rule are the rules in graphics to judge whether a point is in a polygon or not, and the non-zero orbit rule is the default rule of Canvas. If you want to know more about these two rules, you can consult the data yourself, so there is no need to increase the length of the introduction.
After the introduction of the input parameters above, then everyone can guess the output parameters of the isPointInPath method, that is, true and false.
Use isPointInPath
Let's start with a simple demo:
Const canvas = document.getElementById ('canvas') const ctx = canvas.getContext (' 2d') ctx.beginPath () ctx.moveTo (10,10) ctx.lineTo (10,50) ctx.lineTo (50,50) ctx.lineTo (50,10) ctx.fillStyle= 'black' ctx.fill () ctx.closePath () canvas.addEventListener (' click', function (e) {const canvasInfo = canvas.getBoundingClientRect () console.log (ctx.isPointInPath (e.clientX-canvasInfo.left) E.clientY-canvasInfo.top))})
As shown in the figure, the gray part is the area occupied by Canvas, and the black is the area where we actually added the event. After we clicked on the black area, we actually did what we wanted, and the printed value was true. It seems that Canvas's incident monitoring is so simple to solve, but is it really that simple? It's obviously impossible! Let's take another example, there are two areas at this time, and we need to bind them to different events:
Const canvas = document.getElementById ('canvas') const ctx = canvas.getContext (' 2d') ctx.beginPath () ctx.moveTo (10,10) ctx.lineTo (10,50) ctx.lineTo (50,50) ctx.lineTo (50,10) ctx.fillStyle= 'black' ctx.fill () ctx.closePath () ctx.beginPath () ctx.moveTo (100150) ctx.lineTo (100150) ctx.lineTo (150150) ctx.lineTo Ctx.fillStyle= 'red' ctx.fill () ctx.closePath () canvas.addEventListener (' click', function (e) {const canvasInfo = canvas.getBoundingClientRect () console.log (ctx.isPointInPath (e.clientX-canvasInfo.left, e.clientY-canvasInfo.top))})
At this point, the result is no longer what we expected. When you click on the black area, the printed value is false, and when you click on the red area, the printed value is true.
In fact, the reason is very simple, because of the above code, we have actually created two Path, and the isPointInPath method actually only detects whether the current point is in the last Path, and the red area in the example is the last Path, so only when you click on the red area can the isPointInPath method be judged to be true. Now let's modify the code:
Const canvas = document.getElementById ('canvas') const ctx = canvas.getContext (' 2d') let drawArray = [] function draw1 () {ctx.beginPath () ctx.moveTo (10,10) ctx.lineTo (10,50) ctx.lineTo (50,50) ctx.lineTo (50,10) ctx.fillStyle= 'black' ctx.fill ()} function draw2 () {ctx.beginPath () ctx.moveTo (100,100) ctx.lineTo Ctx.lineTo (150,150) ctx.lineTo (150,100) ctx.fillStyle= 'red' ctx.fill () ctx.closePath ()} drawArray.push (draw1, draw2) drawArray.forEach (it = > {it ()}) canvas.addEventListener (' click', function (e) {ctx.clearRect (0,0,400) Const canvasInfo = canvas.getBoundingClientRect () drawArray.forEach (it = > {it () console.log (ctx.isPointInPath (e.clientX-canvasInfo.left, e.clientY-canvasInfo.top))})
We made a big change to the above code. We put each Path into a separate function and push them into an array. When the click event is triggered, we empty the Canvas and redraw the array, each time we draw a Path to make a judgment, so that when we call the isPointInPath method, we can get the current last Path in real time, and then determine the Path in which the current point is located.
Now that we have indirectly implemented individual event listening for each Path, the way it is implemented needs to be redrawn again and again, so is there a way to listen for events without redrawing?
First of all, we need to know that the reason for redrawing again and again is because the isPointInPath method is the last Path for listening, but when we introduced this method, we said that its first parameter is a Path object. When we pass this parameter, Path will no longer fetch the last Path but use the Path we passed in. Now let's use a demo to verify its feasibility:
Const canvas = document.getElementById ('canvas') const ctx = canvas.getContext (' 2d') const path2 = new Path3D (); path2.rect (10,10,100100); ctx.fill (path2) const path3 = new Path3D (); path3.moveTo (220,60); path3.arc (170,60,50,0,2 * Math.PI) Ctx.stroke (path3) canvas.addEventListener ('click', function (e) {console.log (ctx.isPointInPath (path2, e.clientX, e.clientY)) console.log (ctx.isPointInPath (path3, e.clientX, e.clientY))})
We click on the left graphics, print true,false;, click on the right graphics, print false,true. The printing results show that there is no problem, but as its compatibility needs to be improved, it is recommended to use redrawing to listen for events.
Conclusion
Canvas event monitoring is almost done here, the principle is very simple, everyone should be able to grasp.
Github address, welcome to start
Appendix
I wrote a demo myself.
Const canvas = document.getElementById ('canvas') class rectangular {constructor (ctx, {top = 0, left = 0, width = 30, height = 50 Background = 'red'}) {this.ctx = ctx this.top = top this.left = left this.width = width this.height = height this.background = background} painting () {this.ctx.beginPath () this.ctx.moveTo (this.left, this.top) this.ctx.lineTo (this.left + this.width This.top) this.ctx.lineTo (this.left + this.width, this.top + this.height) this.ctx.lineTo (this.left, this.top + this.height) this.ctx.fillStyle = this.background this.ctx.fill () this.ctx.closePath ()} adjust (left, top) {this.left + = left this.top + = top}} class circle {constructor (ctx) {center = [], radius = 10, background = 'blue'}) {this.ctx = ctx this.center = [center [0] = undefined? Radius: center [0], center [1] = undefined? Radius: center [1]] this.radius = radius this.background = background} painting () {this.ctx.beginPath () this.ctx.arc (this.center [0], this.center [1], this.radius, 0, Math.PI * 2, false) this.ctx.fillStyle = this.background this.ctx.fill () this.ctx.closePath ()} adjust (left) Top) {this.center [0] + = left this.center [1] + = top}} class demo {constructor (canvas) {this.canvasInfo = canvas.getBoundingClientRect () this.renderList = [] this.ctx = canvas.getContext ('2d') this.canvas = canvas this.rectangular = (config) = > {let target = new rectangular (this.ctx) {... config}) this.addRenderList (target) return this} this.circle = (config) = > {let target = new circle (this.ctx) {... config}) this.addRenderList (target) return this} this.addEvent ()} addRenderList (target) {this.renderList.push (target)} itemToLast (index) {const lastItem = this.renderList.splice (index, 1) [0] this.renderList.push (lastItem)} painting () {this.ctx.clearRect (0,0, this.canvasInfo.width) This.canvasInfo.height) this.renderList.forEach (it = > it.painting ())} addEvent () {const that = this let startX, startY canvas.addEventListener ('mousedown', e = > {startX = e.clientX startY = e.clientY let choosedIndex = null this.renderList.forEach ((it, index) = > {it.painting () if (this.ctx.isPointInPath (startX)) StartY) {choosedIndex = index}}) if (choosedIndex! = = null) {this.itemToLast (choosedIndex)} document.addEventListener ('mousemove', mousemoveEvent) document.addEventListener (' mouseup') MouseupEvent) this.painting ()}) function mousemoveEvent (e) {const target = that.renderList [that.renderList.length-1] const currentX = e.clientX const currentY = e.clientY target.adjust (currentX-startX CurrentY-startY) startX = currentX startY = currentY that.painting ()} function mouseupEvent (e) {const target = that.renderList [that.renderList.length-1] const currentX = e.clientX const currentY = e.clientY target.adjust (currentX-startX, currentY-startY) startX = currentX startY = currentY that.painting () document.removeEventListener ('mousemove' MousemoveEvent) document.removeEventListener ('mouseup', mouseupEvent)}} const yes = new demo (canvas) .examples ({}) .roommates ({top: 60, left: 60, background:' blue'}) .roommates ({top: 30, left: 20, background: 'green'}) .neighbors () .neighbors ({center: [100,30], background:' red' Radius: 5}) .painting () these are the contents of the article on "how to add events to Canvas in html5" I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.