How to implement binding event listening through Canvas in Front-end Development
This article introduces the knowledge of "how to implement binding event monitoring through Canvas in front-end development". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
In HTML, only listener functions can be bound for elements / tags; there is only one element in the Canvas drawing-canvas, and each graph / image is not an element, and event binding cannot be done directly.
Solution: "event delegation"-let canvas listen on all events and calculate whether the event occurrence coordinate points are within the range of a graph / image.
Event binding can be done for standard geometry
Event binding for non-standard geometry is very troublesome.
Canvas draw Music player # range1,#range2 {height:3px; position: relative; border: 0; outline: 0; box-shadow: 0 3px # 300 inset;} # range1 {width:250px; left:-275px; top:-10px } # range2 {transform:rotate (- 90deg); width:50px; left:-320px; top:-50px;} var ctx1=can1.getContext ('2d'); var img=new Image (); var img1=new Image (); var img2=new Image (); img.src= "img/bg.jpg" / / drawing background / / must be assigned in front of img1,img2, otherwise it will cover img1.src= "img/loop.jpg"; img2.src= "img/play1.png"; var progress=0;// set weight to determine whether all pictures are loaded img.onload=function () {/ / background pictures are loaded, yes-> start drawing progress+=20 (progress==60) & & star ();} img1.onload=function () {/ / background picture loading is complete, yes-> start drawing progress+=20; (progress==60) & & star ();} img2.onload=function () {/ / background picture loading is complete, yes-> start drawing progress+=20 (progress==60) & & star ();} / / start drawing function star () {ctx1.drawImage (img,0,0300500); / / drawing background loop (); / / drawing cycle img1 ctx1.drawImage (img2100350100100); / / drawing 2} / / Loop event, click on the global variable var iS0; var time=null; var ispause=true of the event / / Loop function function loop () {ctx1.save (); / / Save brush's current state ctx1.translate (150165); / / translate ctx1.rotate (i*Math.PI/180); / / rotate ctx1.drawImage (img1,-65,-65); / / draw ctx1.restore () / / reset the state before the brush / / paint two circles ctx1.strokeStyle= "# 000"; ctx1.lineWidth=20; ctx1.arc (150Magne165); ctx1.beginPath (); ctx1.strokeStyle=" # 303 "; ctx1.lineWidth=10; ctx1.arc (150Magne165); ctx1.stroke (); item10 / / Click the event can1.onclick=function (e) {var x = e.offsetX; var y = e.offsetY; / / console.log (XMague y); if ((xMel 150) * (XMAE 150) + (yMuk 400) * (yMuk 400)