gpt4 book ai didi

javascript - 使用双上下文获取 Canvas 上的真实鼠标位置

转载 作者:行者123 更新时间:2023-12-02 21:01:18 24 4
gpt4 key购买 nike

有人要求我在使用 Canvas 的 html5 制作的游戏中获取鼠标坐标。作为第一个测试,尝试使用以下函数读取鼠标位置。但此函数仅读取鼠标位置并考虑 Canvas 的尺寸。

发生的情况是游戏的舞台比 Canvas 更大,并且此功能无法显示 Angular 色在舞台上的真实位置。

我在进行搜索时注意到 Canvas 的“后面”存在于 map (.png) 上,且像素尺寸已确定。 Canvas 的工作方式类似于相机来查看 map 的一部分。

是否可以调整我的函数来读取 map 的尺寸​​,然后找到玩家的实际坐标?

        var canvas = document.querySelector('canvas');
var ctx = canvas.getContext("2d");

canvas.addEventListener("click", function(e) {
var cRect = canvas.getBoundingClientRect();

var scaleX = canvas.width / cRect.width;
var scaleY = canvas.height / cRect.height;

var canvasX = Math.round((e.clientX - cRect.left) * scaleX);
var canvasY = Math.round((e.clientY - cRect.top) * scaleY);

console.log("X: "+canvasX+", Y: "+canvasY);
});

这个函数只会根据 Canvas 的大小给我鼠标的位置,但 map 更大,我在这里留下一张解释性图片。

enter image description here

希望你能理解我。提前致谢。

最佳答案

世界 <=> View

为了建立白话,使用的术语是

  • 世界:世界/游戏场/(红色框)的坐标系(以像素为单位)。
  • View : Canvas /相机/(蓝色框)的坐标系(以 Canvas 像素为单位)。

正如评论中所指出的。您需要 View 原点。这是 Canvas 左上角在世界空间中的坐标。

您还需要知道 View 比例。这就是 Canvas 相对于世界的大小。

必填信息

const world = {width: 2048, height: 1024}; // Red box in pixels
const view = { // blue box
origin: {x: 500, y: 20}, // in world scale (pixels on world)
scale: {width: 1, height: 1}, // scale of pixels (from view to world)
}

没有此信息,您无法进行转换。它必须存在,因为需要将世界内容渲染到 Canvas 上。

注意,如果比例为1,则只能在 Canvas 渲染系统中推断它们。如果找不到比例,请使用 1

注意此答案假设 View 没有旋转。

查看=>世界

以下函数将从 View 坐标转换为世界坐标。

function viewToWorld(x, y) { // x,y pixel coordinates on canvas
return {
x: x * view.scale.width + view.origin.x,
y: y * view.scale.height + view.origin.y
}; // return x,y pixel coordinates in world
}

在客户端为 Canvas 的鼠标事件中使用

function mouseEvent(event) {
// get world (red box) coords
const worldCoord = viewToWorld(event.clientX, event.clientY);

// normalize
worldCoord.x /= world.width;
worldCoord.y /= world.height;
}

世界 => View

您可以反转转换。即通过以下函数从世界坐标移动到 View 坐标。

function normalWorldToView(x, y) { // x,y normalized world coordinates
return {
x: (x * world.width - view.origin.x) / view.scale.width,
y: (y * world.height - view.origin.y) / view.scale.height
}; // return x,y pixel on canvas (view)
}

以像素为单位

function worldToView(x, y) { // x,y world coordinates in pixels
return {
x: (x - view.origin.x) / view.scale.width,
y: (y - view.origin.y) / view.scale.height
}; // return x,y pixel on canvas (view)
}

关于javascript - 使用双上下文获取 Canvas 上的真实鼠标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61349439/

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