Anonymous Anonymous - 2 months ago 14
Javascript Question

How do I implement select of hero in canvas?

I have got Hero to canvas. How do i select it and open context menu?

select hero

I may added listener only to canvas, becuse class Image not contains this method.

Simple code:

context.drawImage(hero, heroX, heroY);
context.globalCompositeOperation = "destination-in";
context.drawImage(mask, heroX, heroY);
context.globalCompositeOperation = "destination-over";

function getElementPosition(obj) {
var curleft = 0,
curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {
x: curleft,
y: curtop
return undefined;

canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
var elementPos = getElementPosition(hero); //doesn't work
}, false);


You need to store the hero's coordinates and check for them in the mousemove callback. offsetLeft and offsetTop work for DOM elements, not for pixels drawn on a canvas.

Not possible to give you a more accurate answer from the code you provided. heroX and heroY look like something you should use, but again, without seeing what they are, it's impossible to tell.