gpt4 book ai didi

javascript - CSS 缩放后 Canvas 上的鼠标坐标

转载 作者:太空宇宙 更新时间:2023-11-04 02:05:55 26 4
gpt4 key购买 nike

我试图在 HTML5 页面的 Canvas 元素上定位鼠标的坐标。

我创建的 Canvas 具有一定的高度和宽度,例如 700x700。当我将鼠标悬停在 Canvas 上时,我希望能够知道鼠标的 X、Y。这工作正常,直到我在 HTML 文件中使用 CSS 拉伸(stretch)我的 Canvas ...

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

    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>

最佳答案

鼠标坐标以显示像素为单位。要将其转换为 Canvas 坐标,您需要相应地缩放它们。

一种方法是:

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

如本例所示:

const status = document.getElementById("coords");

const canvas = document.createElement("canvas");
canvas.width = 700;
canvas.height = 700;
document.body.appendChild(canvas);

canvas.addEventListener('mousemove', event => {
const mouseX = event.clientX - canvas.offsetLeft;
const mouseY = event.clientY - canvas.offsetTop;

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

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

关于javascript - CSS 缩放后 Canvas 上的鼠标坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40753016/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com