开发者

How do I attach an event like click() on a square I draw with fillrect()

Hi guys

I work on a simple game: there si a blue square moving in a canvas, if you clic on the square you win if you clic outside you lose. I don't know how to compare the mouse position with the square position... Here is my source code

<head>  
<script type="text/javascript" src="jquery-1.5.2.min.js"></script>  
<script>
var context;
var x=6; // the start position
var y=6; // same
var dx=1; // the speed  
var dy=1; // the speed  


function init()
{
  context= myCanvas.getContext('2d');
  setInterval(draw,6); 
  clicrect();
}

function draw()
{
  context.clearRect(0,0, 300,300);
  context.beginPath();
  context.fillStyle="#0000ff";
  context.fillRect(x,y,50,50);
  context.closePath();
  context.fill();
  // Boundary Logic
if( x<1 || x>250-50) dx=-dx;
if( y<1 || y>300-50) dy=-dy;
x+=dx;
y+=dy;

}

function clicrect() {
$('#myCanvas').click(function (e)
{
    if (e.target == document.getElementById("myCanvas:animated"))  //that's where I am strugglin, I try to compare the mouse position with the blue square position, but the myCanvas:animated don't work.
        ale开发者_如何学Gort("In");
    else
        alert("Out!");
});
}

</script>
</head>
<body onLoad="init();">
  <canvas id="myCanvas" width="300" height="300" >
  </canvas>
</body>

thanks for your help :)


Have a look at a this - looks like a reasonable place to start - elements in canvas are NOT in the DOM so jquery itself cannot interact directly

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜