【问题标题】:How to rotate rectangles in their place on HTML canvas? [duplicate]如何在 HTML 画布上旋转矩形? [复制]
【发布时间】:2016-07-20 18:26:58
【问题描述】:

我在 HTML 画布上旋转矩形时遇到了一些问题。正如您在 JS Fiddle 中看到的,原始图像显示在此处:https://jsfiddle.net/vyx2hbky/。我想要做的是稍微旋转线条,比如 45 度,在它们的位置。

当我取消注释 JS Fiddle 中的注释代码时,就是这样,

ctx.translate(coords[0], coords[1]);
ctx.rotate(Math.PI / 4);

所有原来的矩形都乱了套,看起来一团糟。他们没有在自己的位置旋转,我不确定如何解决这个问题。

我已经查看过之前关于在中心点旋转矩形的 Stack Overflow 问题,但我不确定如何找到每个单独矩形的中心点,以及如何为每个单独的矩形复制此过程画布中的矩形。

我已经尝试过 ctx.translate(coords[0] + c.width / 2, coords[1] + c.height / 2),根据之前的一些 Stack Overflow 答案,但这似乎不起作用。任何指导将不胜感激!

【问题讨论】:

  • context.translate(rect.x+rect.width/2,rect.y+rect.height/2) 然后context.rotate(Math.PI/4)。绘制后,请确保使用context.setTransform(1,0,0,1,0,0) 重置转换。

标签: javascript html css canvas


【解决方案1】:

尝试这样做,就在“var coords = dotPositions[i];”之后:

    ctx.save();
    ctx.translate(coords[0]+5, coords[1]);
    ctx.rotate(Math.PI / 4);
    ctx.rect(-5, 0, 10, 0);
    ctx.fill();
    ctx.stroke();
    ctx.restore();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-15
    • 2012-11-27
    • 1970-01-01
    • 2016-08-05
    • 2019-03-07
    • 2022-11-12
    • 2021-10-07
    • 1970-01-01
    相关资源
    最近更新 更多