Jalepano
Jalepano

Reputation: 51

How to assign onclick on image drawn in canvas?

I'm trying to get an event to work on an image when the user clicks on it.

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!");
    }

Obviously all this code will just let the alert box go off as long as the user clicks in the canvas. The image is 100 by 100 pixels.

Upvotes: 1

Views: 2251

Answers (1)

user1693593
user1693593

Reputation:

First off: You apparently have an error in you code in regards to the image (at least in the example you provide):

var button = new Image();

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

clickhere.src = "clickhere.png";

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

Should be like this for the example to work:

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)
}

The next problem

Canvas doesn't know what we draw into it so we need to make sure we provide all the underlying logic ourselves to handle these sort of things.

For example: Here is one way to check if the region the image was drawn into is clicked:

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!");
    }
}

You might want to convert those semi-absolute bounds to something more dynamic by for example using an image with a custom object where you store its x and y position and so forth. But you should get the idea.

Update:

A modified fiddle here

Upvotes: 1

Related Questions