簡體   English   中英

如何在畫布上繪制的圖像上分配onclick?

[英]How to assign onclick on image drawn in 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像素。

首先,首先,您的圖像顯然存在錯誤(至少在您提供的示例中):

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位置存儲在其中)等將這些半絕對邊界轉換為更動態的對象。 但是你應該明白這個想法。

更新

這里改良小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM