Is there a way to detect canvas lines with jQuery?

社会主义新天地 提交于 2019-12-01 08:29:16

问题


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:

<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>

<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
    window.onload = function(){
        var c=document.getElementById("myCanvas");
        var ctx=c.getContext("2d");
        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();
    };
</script>

I'm using a modified jQuery script that I actually found in another question on here, but now I can't figure out how to detect the line, mainly the difference in color from white to black, in the canvas. I know that this can be done with images, but I haven't seen anyone with something like this.

I guess my real question is, is there a way to detect color changes on a canvas element with jQuery?


回答1:


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));


来源:https://stackoverflow.com/questions/15325283/is-there-a-way-to-detect-canvas-lines-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!