# 转换

画布允许以多种方式转换坐标系。 这与QML项提供的转换非常相似,可以scale(缩放)、rotate(旋转)、translate(平移)坐标系。 与QML的原点毫无关系,变换原点始终是画布的原点。 例如,要围绕路径中心缩放,需要将画布原点平移到路径的中心,还可以将此转换方法应用更复杂的转换中。

import QtQuick

Canvas {
    id: root
    width: 240; height: 120
    onPaint: {
        var ctx = getContext("2d")
            var ctx = getContext("2d");
            ctx.lineWidth = 4;
            ctx.strokeStyle = "blue";

            // translate x/y coordinate system
            ctx.translate(root.width/2, root.height/2);

            // draw path
            ctx.beginPath();
            ctx.rect(-20, -20, 40, 40);
            ctx.stroke();

            // rotate coordinate system
            ctx.rotate(Math.PI/4);
            ctx.strokeStyle = "green";

            // draw path
            ctx.beginPath();
            ctx.rect(-20, -20, 40, 40);
            ctx.stroke();
    }
}

image

除了平移画布,还允许使用scale(x,y)沿着x和y轴缩放,使用rotate(angle)旋转,其中角度使用角度制(360 度 = 2*Math .PI),并可以使用setTransform(m11, m12, m21, m22, dx, dy)进行矩阵变换。

提示

要重置任何转换,可以调用resetTransform()函数将转换矩阵设置回单位矩阵:

ctx.resetTransform()
最后更新: 12/19/2021, 11:55:53 PM