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

Issue with mouse coordinates using HTML5 canvas

本文关键字:鼠标 坐标 问题 HTML5 使用      更新时间:2023-09-26

对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>

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

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

我调整了两件事。(1)你声明了var mouseX,但是你设置了一个"mouseX";(2)使用x, y,宽度和高度,而不是使用左,右,顶部和底部坐标来定义您的可点击区域。这更适合画布布局。

下面是更新后的代码:

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();
    }
}