gpt4 book ai didi

javascript - Canvas 访问平移背景图像的平移位置坐标

转载 作者:行者123 更新时间:2023-11-28 10:03:26 25 4
gpt4 key购买 nike

无法弄清楚如何找到背景相对于 Canvas 的翻译位置。我有字符坐标,并且有 Canvas 内鼠标单击的坐标,但不知道如何找到偏移量。

在 Canvas 中,当我单击某处时,无论我的 Angular 色在哪里,我都会从 (0,0) - (650,575) 获得一个 (x,y) 值,即窗口的大小。如果 Angular 色位于 Canvas 上的 (2000, 1500),我的单击/触摸输入将始终将 Angular 色向上和向左发送到背景坐标上的 0,0。

起初我认为应该从最大宽度中减去玩家的 X 位置,然后添加屏幕宽度一半的偏移量,并对 Y 位置执行相同的操作,但这不起作用。

然后我尝试从当前玩家的 x,y 值中减去屏幕宽度/高度的一半,但这不起作用。

有人给我指出正确的方向吗,这看起来很简单,但我不知道数学课已经好几年了???谢谢

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 650;
canvas.height = 575;
var WIDTH=5000; //level width
var HEIGHT=3750; //level height
ctx.translate(-WIDTH*.5,-HEIGHT*.5); //starts in center of background

我的播放器开始加载的位置:

hero.x = WIDTH*.5+325; //offset half canvas width
hero.y = HEIGHT*.5+275; //offset half canvas height

背景:

ctx.drawImage(bgImage,  BGsrcX , BGsrcY, 1250 , 938 ,-150, -150, BGdestW, BGdestH); `//image is stretched to 5000x3750`

这是我正在使用的鼠标输入

  if(navigator.userAgent.match(/(iPhone)|(iPod)|(iPad)/i)){
document.addEventListener('touchstart', function(e) {
if(e.touches.length == 1){ // Only deal with one finger
var touch = e.touches[0]; // Get the information for finger #1
var x = touch.pageX - canvas.offsetLeft;
var y = touch.pageY - canvas.offsetTop;
//clickEvent(x,y); //call your function to manage tweets
}
},false);
}
else{
document.addEventListener('mousedown',function(e) {
var x = e.pageX - canvas.offsetLeft;
var y = e.pageY - canvas.offsetTop;
console.log(x+":"+y);
clickEvent(x,y); //call your function to manage tweets
},false);
}

对于键盘输入实际平移背景:

if(16 in keysDown && 38 in keysDown && hero.y > 200) {ctx.translate(0,12); }

最佳答案

不要使用半翻译和未翻译的坐标,翻译鼠标单击坐标和 Canvas 坐标。

然后您可以使用简单的减法来找到偏移量,并使用距离公式来找到距离。

关于javascript - Canvas 访问平移背景图像的平移位置坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8737113/

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