How to detect if a mouse pointer hits a line already drawn on an HTML 5 canvas

后端 未结 1 1098
孤街浪徒
孤街浪徒 2021-01-15 11:46

I am trying to figure out how one can detect if the user\'s mouse hits a line on an HTML 5 canvas with jQuery.

Here is the code that generates the canvas lines:

相关标签:
1条回答
  • 2021-01-15 12:34

    Its possible to do with javascript. In fact you aren't using any jQuery in your example above. An easy way to do it is by grabbing the pixel data from the canvas, and checking the alpha at the specified x and y position. If the alpha isn't set to 0, then you have something drawn on the canvas. Below is a function I put together real quick that does that.

    Live Demo

    var canvas = document.getElementById("canvas"),
        ctx = canvas.getContext("2d"),
        width = 400;
    height = 400;
    
    canvas.width = canvas.height = 200;
    
    // draw
    ctx.moveTo(40, 0);
    ctx.lineTo(40, 360);
    ctx.stroke();
    ctx.moveTo(80, 400);
    ctx.lineTo(80, 40);
    ctx.stroke();
    ctx.moveTo(120, 0);
    ctx.lineTo(120, 360);
    ctx.stroke();
    ctx.moveTo(160, 400);
    ctx.lineTo(160, 40);
    ctx.stroke();
    
    function detectLine(x, y) {
        var imageData = ctx.getImageData(0, 0, width, height),
            inputData = imageData.data,
            pData = (~~x + (~~y * width)) * 4;
    
        if (inputData[pData + 3]) {
            return true;
        }
    
        return false;
    }
    
    canvas.addEventListener("mousemove", function(e){
        var x  = e.pageX,
            y = e.pageY;
        console.log(detectLine(x, y));
    });
    
    console.log(detectLine(40, 100));
    console.log(detectLine(200, 200));
    
    0 讨论(0)
提交回复
热议问题