检测鼠标单击画布绘图

时间:2014-09-01 09:33:12

标签: javascript html5 canvas

我目前遇到问题 -
我有一个重新调整大小的画布(基于resize事件重新调整大小),上面画了一些矩形,这些矩形现在有X,Y,WIDTH和HEIGHT属性...
 当我调整画布大小时,一切都很好,形状相对于画布尺寸绘制 问题是它们的X和Y没有变化,所以当我尝试使用任何鼠标事件来检测鼠标位置是否在矩形内时它除了开始之外不起作用,例如 - 如果我在窗口大小为1024 * 768时初始化所有内容,那么矩形X和Y位置将是50乘50,如果我用鼠标点击X:50它会碰撞并检测到它,但是,如果我我会调整浏览器窗口的大小,让我们说,689 * 400,我会点击它不起作用的矩形。

有人有解决方案吗?

TL; DR - 如何在重新调整窗口大小后检测到具有X,Y的矩形的点击?

画布调整大小 -

window.addEventListener("resize", function() {
                        self.canvas.fitToBrowser();
                    });

Kanivas.prototype.fitToBrowser = function() {
    if (this.canvas.width < window.innerWidth)
    {
        this.canvas.width = window.innerWidth;
        this.cHeight = this.canvas.width;
    }

    if (this.canvas.height < window.innerHeight)
    {
        this.canvas.height = window.innerHeight;
        this.cHeight = this.canvas.height;
    }
};

MouseDown处理程序 -

this.canvas.addEventListener("mousedown",
            function(kanivas, event) {
                console.log(state);
                self.mouseDownHandler(kanivas, event);
            }.bind(null, this), false);

Kanivas.prototype.mouseDownHandler = function(kanivas, e) {
    var shape = null;
    var i = kanivas.shapes.length;
    while (i--) {
        shape = kanivas.shapes[i];
        if (shape.isInside !== undefined && shape.isInside(e.clientX, e.clientY)) {
            shape.mouseDownHandler();
        }
    }
};
 //Inside the rectangle object
 this.isInside = function(x, y) {
        return ((x >= this.x && x <= this.x + this.width) &&
                (y >= this.y && y <= this.y + this.height));
    };

0 个答案:

没有答案
相关问题