CSS缩放后的画布上的鼠标坐标

时间:2016-11-22 22:43:30

标签: javascript html css html5 canvas

我试图在HTML5页面的canvas元素上找到鼠标的坐标。

我将画布创建为一定的高度和宽度,例如700x700。当我将鼠标悬停在画布上时,我希望能够知道鼠标的X,Y。这很好用,直到我在HTML文件中使用CSS拉伸我的画布......

这是我的javascript文件:     函数Sprite(路径)     {         this.img = new Image();         this.img.onload =已加载;         this.img.src = path;

    function loaded()
    {
        console.log("Loaded picture");
    }
}

function drawSprite(sprite, ctx)
{
    console.log("drawing picture");
    ctx.drawImage(sprite.img,10,10);
}

//------------------------------------------

function Game()
{
    this.canvas = document.createElement("canvas");
    document.body.appendChild(this.canvas);
    this.canvas.width = 700;
    this.canvas.height = 700;
    this.context = this.canvas.getContext("2d");    

    var ctx = this.context;

    ctx.canvas.addEventListener('mousemove', function(event){
        var mouseX = event.clientX - ctx.canvas.offsetLeft;
        var mouseY = event.clientY - ctx.canvas.offsetTop;
        var status = document.getElementById("coords");
        status.innerHTML = mouseX+" | "+mouseY;

    });


    this.objects = new Array();
    this.objects.push(new Sprite("dog.png"));
}

function drawGame(g)
{
    console.log("I'm here");
    for(var i=0;i<g.objects.length;i++)
    {
        drawSprite(g.objects[i], g.context);
    }
}

function drawLine(g)
{
    g.context.moveTo(0,0);
    g.context.lineTo(100,100);
    g.context.stroke();
}

//------------------

window.addEventListener('load',function(event){startgame();});
var globalGame;

function startgame()
{
    globalGame = new Game();
    drawGame(globalGame);
    drawLine(globalGame);
}

这是我的HTML文件

<html>
    <head>
        <script src="functions.js"></script>
        <style>
            canvas
            {
                width:90%;
                height:90%;
            }
        </style>
    </head>
    <body>

    <h1 id="coords">0 | 0</h1>
    </body>
<html>

1 个答案:

答案 0 :(得分:1)

鼠标坐标位于显示像素中。要将其转换为画布坐标,您需要相应地缩放它们。

这样做的一种方法是:

var canvasX = mouseX * canvas.width / canvas.clientWidth;
var canvasY = mouseY * canvas.height / canvas.clientHeight;

如下例所示:

&#13;
&#13;
var canvas = document.createElement("canvas");
  document.body.appendChild(canvas);
  canvas.width = 700;
  canvas.height = 700;
var ctx = canvas.getContext("2d");    

ctx.canvas.addEventListener('mousemove', function(event){
  var mouseX = event.clientX - ctx.canvas.offsetLeft;
  var mouseY = event.clientY - ctx.canvas.offsetTop;
  var status = document.getElementById("coords");

  // scale mouse coordinates to canvas coordinates
  var canvasX = mouseX * canvas.width / canvas.clientWidth;
  var canvasY = mouseY * canvas.height / canvas.clientHeight;

  status.innerHTML = mouseX+" | "+mouseY+"<br>"+canvasX+" | "+canvasY;
});
&#13;
canvas {
  width:250px;
  height:250px;
  background-color:#f0f;
}
&#13;
<div id="coords">??? | ???<br>??? | ???</div>
&#13;
&#13;
&#13;