简体   繁体   中英

How to make this canvas rectangle clickable?

ctx.fillStyle = "#9b958c";
ctx.fillRect(sampleRectX, sampleRectY, sampleRectW, sampleRectH);
ctx.fillStyle = "#fff";
ctx.fillText("Click here to play again.", sampleTextX, sampleTextY);

This rectangle must be clickable. This approach https://stackoverflow.com/a/16455006/3677742 seems to be the answer to my problem, but the event listener for the mouse click just doesn't work and I don't know why. I'm trying to do this:

canvas.addEventListener("click", getClickPosition, false);

function getClickPosition(e) {
    var xPosition = e.clientX;
    var yPosition = e.clientY;
    if ((sampleRectX <= xPosition) && (sampleRectX + sampleRectW >= xPosition) && (sampleRectY <= yPosition) && (sampleRectY + sampleRectH >= yPosition) {
        if (lose===true) {
            playAgain = true;
        };
    };
};

If it is relevant to know, my code is organized like this:

//Variables here
...

//Objects (player, enemy...)
...

function main() {
    ...
};

function init() {
    ...
};

function update() {
    ...
};

function draw() {
    ...
    if (gameStarted===true) {
        ...
        if (lose===true) {
            ...
            ctx.fillStyle = "#9b958c";
            ctx.fillRect(sampleRectX, sampleRectY, sampleRectW, sampleRectH);
            ctx.fillStyle = "#fff";
            ctx.fillText("Click here to play again.", sampleTextX, sampleTextY);
};

main();

I'm a beginner on coding, so I'm sorry if I'm asking something too "noob-level".

((sampleRectX < xPosition) && 
 (sampleRectX + sampleRectW > xPosition) && 
 (sampleRectY < yPosition) && 
 (sampleRectY + sampleRectH > yPosition)
)

You got it almost right, you were just missing a parenthesis at the end

If you inspect the mouse event returned from the event listener (which you always should, always inspect everything you get from APIs and see how it works), you'll see there are different values.

You took e.clientX, and so did I, and it didn't work for me because the canvas on my testpage happened not to be located at 0,0 (like it almost always does)

To get the correct values, I had to get e.offsetX and e.offsetY

Shamefully I don't know exactly what each of the individual coordinates on the mouse event stand for, but i'm going to look it up and update my answer.

I hope this time it solves your problem.

If in doubt always debug using console.log() to inspect what's actually happening and what an APIs throw at you.

(If it still doesn't solve your problem put console.log() everywhere in your code where you don't know if it executes and check where it doesn't.)

I made you an example fiddle http://jsfiddle.net/cxyTV/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM