【问题标题】:Convert position coordinates to canvas coordinates将位置坐标转换为画布坐标
【发布时间】:2014-12-13 19:50:01
【问题描述】:

我必须将游戏中的位置坐标转换为 HTML5 Canvas 坐标。

给定的坐标看起来像

-2159.968750,-926.968750
-2159.968750,-704.031250
-2026.847167,-926.993835

给定的坐标不像画布坐标那样代表像素。

有没有什么方法可以将任何给定的坐标转换为相应的画布坐标,只需几个校准坐标?

例如,我知道画布上的坐标 #1 是 (66, 980),而画布上的坐标 #2 是 (66, 933)。

提前致谢

【问题讨论】:

    标签: javascript html canvas html5-canvas


    【解决方案1】:

    您可以将游戏值映射到画布坐标中,如下所示:

    // fit map game values into canvas coordinates
    // value is a game coordinate to be translated into a canvas coordinate
    // gameLow & gameHigh are the min & max out of all the game values
    // canvasLow & canvasHigh are the available canvas coordinates
    // to use the entire canvas canvasLow==0 & canvasHigh==the canvas width in pixels
    function mapRange(value, gameLow, gameHigh, canvasLow, canvasHigh) {
        return ( canvasLow + 
            (canvasHigh - canvasLow) * (value - gameLow) / (gameHigh - gameLow) );
    }
    

    示例用法:

    给定一个游戏 X 值数组,找出 X 的最小值和最大值。

    // Given an array of X values
    var gameValuesX=[-2159.968750, -2159.968750, -2026.847167];
    
    // Find the min & max X
    var rangeX=calcgameMinMax(gameValues);
    
    function calcgameMinMax(a){
        var min=100000000;
        var max=-100000000;
        for(var i=0;i<a.length;i++){
            var value=a[i];
            if(value<min){min=value;}
            if(value>max){max=value;}
        }
        return({min:min,max:max});
    }
    

    对于每个游戏 X,调用 mapRange() 提供游戏的 max-X 和 min-X 游戏坐标值以及画布 min-X 和 max-X 坐标值。

    for(var i=0;i<gameValuesX.length;i++){
    
        // where canvas.width is the width of the canvas in pixels
        console.log( mapRange( gameValuesX[i], rangeX.min, rangeX.max, 0, canvas.width ) );
    
    }
    

    对游戏 Y 值做同样的事情...

    祝你的项目好运!

    【讨论】:

      【解决方案2】:

      您最可能想要的是在画布上显示游戏虚拟世界的一部分。

      • 首先,您必须确定此视图 rect 并以某种方式存储它。
      最简单的:

      var viewRect = { x : -3000, y:-3000, width: 6000, height:6000 } ;
      

      • 然后,当你想画画时,我建议你让画布为你做数学运算并使用变换。

      所以你猜到了'canvasWidth'和'canvasHeight'初始化,绘图代码看起来像:

      context.clearRect(0,0,canvasWidth, canvasHeight);
      context.save();
      var ratio = canvasWidth / viewRect.width;
      context.scale(ratio, ratio);
      context.translate(-viewRect.x, -viewRect.y);
      //
      // do your drawings here in world coordinates.
      context.fillStyle='black';
      context.fillRect(-2000, -800, 300, 300);
      //
      context.restore();
      

      请注意,您必须保存()和恢复()上下文以在每次渲染时保持正确。

      (您也可能不使用保存/恢复并使用'setTransform(1, 0, 0, 1, 0, 0);'来重置转换。)

      最简单的 jsbin 在这里: http://jsbin.com/hudaqoqavu/1/

      【讨论】:

        猜你喜欢
        • 2011-10-15
        • 1970-01-01
        • 1970-01-01
        • 2021-09-06
        • 2014-07-02
        • 2015-03-13
        • 2019-08-24
        • 2014-07-21
        • 1970-01-01
        相关资源
        最近更新 更多