简体   繁体   中英

Javascript Code For HTML5 Canvas Not Working

I wrote a code that doesn't work. It had a bug earlier, which was fixed. But now there is another bug: it won't draw a rectangle on the canvas. The console didn't detect the error. Here is the code:

13.      var canvas=document.getElementById("canvas")
14.      var ctx=canvas.getContext("2d")
15.      function getMousePos(canvas,evt){
16.          var rect=canvas.getBindingClientRect()
17.          return{
18.               x:evt.clientX-rect.left,
19.               y:evt.clientY-rect.top
20.          }
21.      }
22.      canvas.addEventListener("mouseclick",function(evt){
23.           var mousePos=getMousePos(canvas,evt)
24.           ctx.fillRect(mousePos.x-15,mousePos.y-15,10,10)
25.      },false)

事件是click而不是mouseclick

Change this line:

var rect=canvas.getBindingClientRect()

to

var rect=canvas.getBoundingClientRect();

and

canvas.addEventListener("mouseclick",function(evt) { ... 

to

canvas.addEventListener("click",function(evt) { ...

and it should work.

See ONLINE DEMO HERE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM