且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有没有办法用jQuery检测画布线?

更新时间:2022-12-12 23:07:23

实际上你没有在上面的例子中使用任何jQuery。一个简单的方法是从画布中抓取像素数据,并在指定的x和y位置检查alpha。如果alpha没有设置为0,那么你在画布上绘制了一些东西。下面是我把这个功能放在一起的功能。

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