Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image Click Event in HTML5 Canvas

I have a HTML5 canvas and I have added an image in it and I want to call click event of image but event doesn't fire. I am writing a html code and some code of jqmobile

<html>
<head>
    <script src="jquery-1.10.2.min.js"></script>
    <script src="jquery.mobile-1.2.1.js"></script>
    <script src="jquery.mobile-1.2.1.min.js"></script>
</head>
<body>
    <canvas id="canvas1" style="position: absolute; left: 0px; top: 0px;" width="1280" height="960">This text is displayed if your browser does not shown.
    </canvas>
    <script>
        $(function () {

            var ctx = document.getElementById("canvas1").getContext("2d");
            var imgBasket = new Image();
            imgBasket.id = "imgBasket";
            imgBasket.src = "Basket.png";
            ctx.drawImage(imgBasket, 580, 260, 200, 200);


            //this jquery mobile event not working in canvas
            $("document").on("vclick", "#imgBasket", function () {
                alert("Hello");
            });
        });
    </script>
</body>
</html>
like image 603
Rizwan Qureshi Avatar asked Apr 07 '14 10:04

Rizwan Qureshi


2 Answers

Now I understand what you are trying to achieve, you want to put an image in a canvas and then use jquery to see when you clicked on the image. Well, sadly, it doesn't work like this. Images in the canvas are no longer dom elements, only the canvas itself is one. This means you can call:

$('#canvas').on('click', function() {});

but you can't call

$("document").on("click", "#canvasImage", function () {});

Because the #canvasImage isn't there, even if the original image was a dom node. If there's really no other way of going with your project, fabricjs might help:

http://fabricjs.com/

like image 57
Jonas Grumann Avatar answered Sep 28 '22 16:09

Jonas Grumann


You cannot add eventlistener on image or shape you drawed on canvas so you have to add eventlistener on pixels where you have drawed the image means for example:

var img=document.getElementById("img1");
//ctx.drawImage(img,x,y,height,width);          
ctx.drawImage(img,10,10,20,20);
    $("#canvas1").on("click",function(event){

var totalOffsetX = 0;
var totalOffsetY = 0;
var canvasX = 0;
var canvasY = 0;
var currentElement = this;

do{
    totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
    totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
}
while(currentElement = currentElement.offsetParent)

canvasX = event.pageX - totalOffsetX;
canvasY = event.pageY - totalOffsetY;

     //Image x y cordinates adding width and height

if((canvasX>=10 && canvasX<=30) && (canvasY>=10 && canvasY<=30))
        {
            alert("canvasX:"+canvasX+"  "+"canvasY:"+canvasY);
        }

});
like image 30
pareshm Avatar answered Sep 28 '22 14:09

pareshm