繁体   English   中英

画布:通过缩放和旋转模拟相机

[英]Canvas: Simulating camera with scale and rotation

我创建了一个相机对象,它的位置充当屏幕的中心。 摄像机允许缩放和旋转。 所以基本上我要做的就是将画布的中心平移到原点,应用比例尺,然后旋转,现在我需要知道需要使用哪种技巧来将其平移回中心,这是到目前为止的代码:

__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它看在centerXcenterY

第三件事是,您将希望避免在缩放时更改纵横比,而是计算画布的纵横比,并让相机视图高度=相机视图宽度*画布比率。

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
});

然后,您可能需要缓存画布大小,以避免在游戏期间访问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);    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM