【问题标题】:HTML5 Canvas: Absolute scaling its contentsHTML5 Canvas:绝对缩放其内容
【发布时间】:2020-11-08 09:48:41
【问题描述】:

我想重新调整画布的内容,所以在一个循环中,我使用rescale 函数。然而,正如我所预料的那样,它在这个例子中起作用:1 -> 2 -> 4 -> 8(因子 = 2)。我想要的是......:1 -> 3 -> 5 -> 7(因子= 2)。所以我不应该用scale,但是什么功能呢?

请注意,默认情况下,我不想也不能使用 CSS 或除画布的 JS API 之外的其他东西。但是,如果没有解决方案,请告诉我您的解决方案,即使它依赖于 CSS...

【问题讨论】:

  • 对不起。错字!我使用规模。不重新缩放。我通过给它 1.0001 作为参数来使用比例。但是,由于它会重新调整画布内容,因此在下一次迭代时,它将考虑新的大小。而且我不希望这种行为。
  • 我不明白为什么它应该起作用? ^^

标签: canvas html5-canvas


【解决方案1】:

绝对比例

您可以通过将当前变换替换为ctx.setTransform 来设置绝对比例

所有其他转换函数ctx.scalectx.translatectx.rotatectx.transform 将转换应用于现有转换。这就是为什么你的规模每次都会翻倍(2,4,8,16)

从而设置一个绝对比例

scale = 1;
ctx.setTransform(scale, 0, 0, scale, 0, 0);

缩放 3

scale += 2;
ctx.setTransform(scale, 0, 0, scale, 0, 0);

再按 5 加 2

scale += 2;
ctx.setTransform(scale, 0, 0, scale, 0, 0);

注意这会替换任何现有的转换。

设置一个完整的统一变换

function setTransform(ctx, x, y, scale, rotate) {
    ctx.setTransform(
         Math.cos(rotate) * scale, Math.sin(rotate) * scale,  // x axis
        -Math.sin(rotate) * scale, Math.cos(rotate) * scale,  // y axis is 90deg CW from x axis
        x, y  // translation as absolute sets origin in px from top left of canvas
    );
}

【讨论】:

    猜你喜欢
    • 2012-05-18
    • 2022-01-10
    • 2014-12-05
    • 1970-01-01
    • 2015-12-21
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    相关资源
    最近更新 更多