【问题标题】:Rotate rect in canvas by its center point with position set将画布中的矩形旋转其中心点并设置位置
【发布时间】:2016-07-30 19:00:59
【问题描述】:

我需要在画布中按其中心点绘制一个旋转的矩形,但我想为其设置xy。我实际上将矩形移动到$b.width / 2$b.height / 2。我不知道该怎么做。

这是我的课程代码。注意:$b 是我的矩形。

do {
    switch($b.t) {
        case 0: { // draw rectangle
            context.fillStyle = $b.tint;
            if($b.rotate) {
                context.save();
                context.translate($b.width, $b.height);
                context.rotate(($b.rotate * Math.PI) / 180);
                context.fillRect(-$b.width / 2, -$b.height / 2, $b.width, $b.height);
                context.restore();
            }else{
                context.fillRect($b.width / 2, $b.height / 2, $b.width, $b.height);
            }
            break;
        }
    }
} while($b = queue[$i ++]);

【问题讨论】:

    标签: javascript html5-canvas


    【解决方案1】:

    所以你想设置一个围绕它自己的中心点旋转的矩形的中心点?

    只需将您想要的 x,y 添加到初始翻译中:

    注意:由于您正在执行简单的非嵌套转换,请以相反的顺序撤消转换。上下文save & restore 可以工作,但您正在保存/恢复所有其他上下文属性,因此效率不高。

    // translate (including the desired centerX & center)
    context.translate(x+b.width/2,y+b.height/2);
    
    // rotate
    context.rotate(($b.rotate * Math.PI) / 180);
    
    // fill the rect offset by half its size
    context.fillRect(-$b.width / 2, -$b.height / 2, $b.width, $b.height);
    
    // unrotate
    context.rotate((-$b.rotate * Math.PI) / 180);
    
    // untranslate
    context.translate(-x-b.width/2,-y-b.height/2);
    

    【讨论】:

      猜你喜欢
      • 2022-11-08
      • 1970-01-01
      • 2014-12-14
      • 2018-06-01
      • 2013-01-27
      • 2015-11-05
      • 1970-01-01
      • 2014-11-09
      • 1970-01-01
      相关资源
      最近更新 更多