gpt4 book ai didi

javascript - Canvas:模拟具有缩放和旋转功能的相机

转载 作者:行者123 更新时间:2023-11-30 17:23:11 25 4
gpt4 key购买 nike

我创建了一个相机对象,它的位置作为屏幕的中心。相机允许缩放和旋转。所以基本上我所做的是我已经将 Canvas 的中心平移到原点,应用比例,然后旋转,现在我需要知道我需要使用什么样的棘手数学来将它平移回中心,这是我目前的代码:

__Stage__.prototype.__cameraTransform = function() {
var canvas = this.__canvas;
var cam = this.camera;
var context = this.__canvasContext;

var cx = canvas.width/2;
var cy = canvas.height/2;
context.translate(-cx,-cy);

var scale = {x: canvas.width/cam.width, y: canvas.height/cam.height};
context.scale(scale.x,scale.y);

var rotation = Math.PI*2 - (cam.rotation%(Math.PI*2));
context.rotate(-rotation);

context.translate(/*What translation to get the point back in the center*/);
}

最佳答案

首先,您可能出于某种原因想要保存上下文或重置上下文。
对于保存/恢复的事情,我猜不出你会如何处理它,并通过以下方式完成重置:

function resetTransform() {
c.setTransform(1, 0, 0, 1, 0, 0);
}

第二件事是你没有提到相机在看哪里,我假设它在看 centerX, centerY

第三件事是,您需要避免在缩放时更改纵横比,因此可以计算 Canvas 的纵横比并让相机 View 高度 = 相机 View 宽度 * Canvas 比例。

Object.defineProperty 允许在你的对象上定义一个属性,所以你可以用一种干净的方式来做:

// at the global level, after document loaded
// OR where you handle the canvas
var canvasRatio = canvas.height / canvas.width;

//... in your camera constructor
Object.defineProperty(this, 'height', {
get: function () {
return canvasRatio * this.width ;
},
set: function (val) {},
enumerable: true
});

然后您可能想要缓存 Canvas 大小以避免在游戏期间访问 DOM。

对于你的旋转计算,我没有得到它但不需要限制在 [0,2*PI] 或类似的:只需使用你拥有的任何弧度值(初始化为 0)。

现在对于你的相机,代码如下:

__Stage__.prototype.__cameraTransform = function() {
var canvas = this.__canvas;
var cam = this.camera;
var context = this.__canvasContext;
// O. reset ??
resetTransform();
//
var cx = this.__canvasWidth/2;
var cy = this.__canvasHeight/2;
// 1 . translate to the middle of the canvas
context.translate(cx,cy);
// 2. scale
var scale = this.__canvasWidth/cam.width;
context.scale(scale,scale);
// 3. translate to where the camera looks
context.translate(-cam.centerX,-cam.centerY);
// 4. rotate
context.rotate(cam.rotation);
}

关于javascript - Canvas:模拟具有缩放和旋转功能的相机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24784789/

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