简体   繁体   中英

identify an object on canvas by a click event

Into this simple code I use an eventListener which doesn't look to work at all. The canvas display an image and the given hitpaint() function is supposed determines whether a click occurs. I cant understand why the eventListener behaves like that. Any insight would be helpful.

mycanv.addEventListener("click", function(e) {
    var output = document.getElementByID("output");
    ctx.fillStyle = 'blue';
    //ctx.clearRect(0,0,100,20);

    if (hitpaint) {
        //ctx.fillText("hit",100,20);                                                                                                                                                                                                           
        output.innerHTML = "hit";
    } else {
        //ctx.fillText("miss",100,20);                                                                                                                                                                                                          
        output.innerHTML = "miss";
    }
}, false);

The hitpaint() function is defined as:

function hitpaint(mouse_event) {
    var bounding_box = mycanv.getBoundingClientRect();
    var mousex = (mouse_event.clientX - bounding_box.left) *
        (mycanv.width / bounding_box.width);
    var mousey = (mouse_event.clientY - bounding_box.top) *
        (mycanv.height / bounding_box.height);
    var pixels = ctx.getImageData(mousex, mousey, 1, 1);

    for (var i = 3; i < pixels.data.length; i += 4) {
        // If we find a non-zero alpha we can just stop and return                                                                                                                                                                            
        // "true" - the click was on a part of the canvas that's                                                                                                                                                                              
        // got colour on it.                                                                                                                                                                                                                  
        if (pixels.data[i] !== 0) return true;
    }

    // The function will only get here if none of the pixels matched in                                                                                                                                                                   
    return false;
}

Finally, the main loop which display the picture in random location into the canvas:

function start() {
    // main game function, called on page load                                                                                                                                                                                            
    setInterval(function() {
        ctx.clearRect(cat_x, cat_y, 100, 100);
        cat_x = Math.random() * mycanv.width - 20;
        cat_y = Math.random() * mycanv.height - 20;
        draw_katy(cat_x, cat_y);
    }, 1000);
}

There are a some issues here:

  • As Grundy points out in the comment, the hitpaint is never called; right now it checks for it's existence and will always return true
  • The mouse coordinates risk ending up as fractional values which is no-go with getImageData
  • Scaling the mouse coordinates is usually not necessary. Canvas should preferably have a fixed size without an additional CSS size
  • Add boundary check for x/y to make sure they are inside canvas bitmap

I would suggest this rewrite:

mycanv.addEventListener("click", function(e) {
    var output = document.getElementByID("output");
    ctx.fillStyle = 'blue';
    //ctx.clearRect(0,0,100,20);

    if (hitpaint(e)) {  // here, call hitpaint()
         //ctx.fillText("hit",100,20);                                                                                                                                                                                                           
        output.innerHTML = "hit";
    } else {
        //ctx.fillText("miss",100,20);                                                                                                                                                                                                          
        output.innerHTML = "miss";
    }
}, false);

Then in hitpaint:

function hitpaint(mouse_event) {

  var bounding_box = mycanv.getBoundingClientRect();

  var x = ((mouse_event.clientX - bounding_box.left) *
    (mycanv.width / bounding_box.width))|0;  // |0 cuts off any fraction
  var y = ((mouse_event.clientY - bounding_box.top) *
    (mycanv.height / bounding_box.height))|0;

  if (x >= 0 && x < mycanv.width && y >= 0 && y < mycanv.height) {
      // as we only have one pixel, we can address alpha channel directly
      return ctx.getImageData(x, y, 1, 1).data[3] !== 0;
  }
  else return false;  // x/y out of range
}

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