0

Here is my code:

<body>
    <canvas id="myCanvas" width="1100" height="600" style="border:1px solid #c3c3c3; cursor:move">
        Your browser does not support the canvas element.
    </canvas>

    <script type="text/javascript">
        var c=document.getElementById("myCanvas");

        var ctx=c.getContext("2d");
        var img=new Image();
        img.src="image.jpg";
        img.id="im";

        img.onload = function(){
            ctx.drawImage(img,0,0,100,100);
            autoRun();
        };

        function autoRun(){
            ctx.clearRect(0, 0, 1100,600);
            img.id="im";
            ctx.drawImage(img,Math.floor((Math.random()*1000)+1),Math.floor((Math.random()*500)+1),70,70);
            setTimeout('autoRun()',1000);
        }   
    </script>
</body>

Here I am using the random method for setting the X and Y coordinates hence the image will move dynamically will move the area of canvas ...

 setTimeout('autoRun()',1000);

The above line will call the autorun function javascript for every sec and that function will clear the canvas and redraw the image with new coordinates....

Now i would like to get the id of the image when we click on it. How can I do that?

Tim
  • 5,435
  • 7
  • 42
  • 62

2 Answers2

1

EDIT- This would not work ! Should this work for you ? Or are there any other complications ?

//This would bind to all image, but you can use
//other jquery selectors to select your perticular 
//image
$('img').click(function(){
  var my_id = $(this).attr('id');
  return false;
});

EDIT

"..The image itself is not available in the DOM, you just created it temporarily to draw it into the canvas. So the canvas holds the content of the image, the image itself is not in the DOM"

Select image within canvas with jQuery

Community
  • 1
  • 1
Anand
  • 14,545
  • 8
  • 32
  • 44
1

I think you should segment the shape of your image (defining its boundary pixels) and then check if when you click inside the canvas, the point selected (the mouse position when clicking) is inside the image shape.

This can be a solution for your problem.

user278064
  • 9,982
  • 1
  • 33
  • 46