使用HTML5画布使用鼠标坐标问题

时间:2014-07-08 23:49:37

标签: javascript html5 canvas

JavaScript / HTML5 Canvas相当新。无法使我的背景的特定区域可单击,以便打开另一个页面。我想要做的是让我选择的背景区域可以点击,而不是整个背景。

<!DOCTYPE HTML>                  
<html lang="en-US">
 <head>
  <meta charset="UTF-8">
  <title>Adventures of Balthazar</title>

  <link rel="stylesheet" type="text/css" href="menu.css" />
  <script type="text/javascript">
  function init(){   
   var canvas = document.getElementById('myCanvas');
   var ctx = canvas.getContext('2d');
   var img = new Image();
   var mouseX = 0;
   var mouseY = 0;
   var btnPlay = new Button(250,555,162,284);

   document.addEventListener('click',mouseClicked,false);

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

   img.src='img/menu.png'

   function Button(xL,xR,yT,yB){
    this.xLeft = xL;
    this.xRight = xR;
    this.yTop = yT;
    this.yBottom = yB;
   }

   Button.prototype.checkClicked = function(){
    if(this.xLeft <= mouseX &&
        mouseX <= this.xRight &&
        this.yTop <= mouseY &&
        mouseY <= this.yBottom) 
     return true;
   }

   function playGame(){
    window.location.href = 'index.html'
   }

   function mouseClicked(e){
    mousex = e.pageX - canvas.offsetLeft;
    mousey = e.pageY - canvas.offsetTop;

    if(btnPlay.checkClicked()) playGame();
   }
  }
  </script>     
 </head> 

 <body onLoad="init()">
  <div id="canvas-container">
   <canvas id="myCanvas" width="800" height="600"> </canvas>
  </div>    
 </body>
</html>

1 个答案:

答案 0 :(得分:0)

这是您的代码的工作版本:

http://jsfiddle.net/3PFXa/1/

我调整了两件事。 (1)你声明了var mouseX但你设置了一个&#34; mousex&#34 ;; (2)使用x,y,width和height而不是使用left,right,top和bottom坐标来定义可点击区域。这适合画布布局。

这是更新后的代码:

function init() {

    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    var img = new Image();
    var mouseX = 0;
    var mouseY = 0;
    var btnPlay = new Button(280, 145, 20, 20);

    document.addEventListener('click', mouseClicked, false);

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

        ctx.fillStyle = "#0f0";
        ctx.rect(btnPlay.x, btnPlay.y, btnPlay.w, btnPlay.h);
        ctx.fill();

    }

    img.src = 'http://cdn.sheknows.com/articles/2013/04/Puppy_2.jpg'

    function Button(x, y, w, h) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
    }

    Button.prototype.checkClicked = function () {

        if ( mouseX > this.x && mouseX < this.x + this.w && mouseY > this.y && mouseY < this.y + this.h) 
            return true;

    }

    function playGame() {
        alert("hello!");
    }

    function mouseClicked(e) {

        mouseX = e.pageX - canvas.offsetLeft;
        mouseY = e.pageY - canvas.offsetTop;

        if (btnPlay.checkClicked()) playGame();
    }
}