如何在画布上绘制的图像上分配onclick?

时间:2013-11-13 04:41:16

标签: javascript html html5 canvas

当用户点击图片时,我正试图让图片处理图片。

var canvas = document.createElement("canvas");
canvas.width = 800;
canvas.height = 600;
canvas.style = "border:2px solid black";
canvas.addEventListener('click', clickReporter, false);
var ctx = canvas.getContext("2d");
document.body.appendChild(canvas);

var clickhere = new Image();

clickhere.onload = function () {
        draw();
};

clickhere.src = "clickhere.png";


function draw() {
ctx.drawImage(clickhere, 200, 200);
}

function clickReporter(e) {
    alert("Thanks for clicking!");
    }

显然,只要用户在画布中单击,所有这些代码都会让警报框关闭。图像为100 x 100像素。

1 个答案:

答案 0 :(得分:1)

首先关闭:您的代码中显然存在错误(至少在您提供的示例中):

var button = new Image();

clickhere.onload = function () {
    draw();
};

clickhere.src = "clickhere.png";

function draw() {
ctx.drawImage(clickhere, 200, 200);
}

这个例子应该是这样的:

var button = new Image();

/// use button for these as well -
button.onload = function () {         /// here
    draw();
};
button.src = "clickhere.png";        /// here

function draw() {
    ctx.drawImage(button, 200, 200); /// and here (or use 'this' instead)
}

下一个问题

Canvas不知道我们绘制了什么,所以我们需要确保自己提供所有底层逻辑来处理这些事情。

例如:这是一种检查图像被绘制区域是否被点击的方法:

function clickReporter(e) { /// assign event to some variable

    /// adjust mouse click position to be relative to canvas:
    var rect = this.getBoundingClientRect(),
        x = e.clientX - rect.left,
        y = e.clientY - rect.top;

    /// check x/y coordinate against the image position and dimension
    if (x >= 200 && x <= (200 + button.width) &&
        y >= 200 && y <= (200 + button.height)) {
        alert("Thanks for clicking!");
    }
}

您可能希望将这些半绝对边界转换为更动态的内容,例如使用带有自定义对象的图像,您可以在其中存储x和y位置,依此类推。但你应该明白这一点。

更新

modified fiddle here