我正在尝试在用户单击图像时让事件在图像上运行。
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!");
}
显然,只要用户在 Canvas 中单击,所有这些代码都会让警报框关闭。该图像为 100 x 100 像素。
最佳答案
首先:您的代码中显然存在与图像有关的错误(至少在您提供的示例中):
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
关于javascript - 如何在 Canvas 上绘制的图像上分配onclick?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19945442/