gpt4 book ai didi

javascript - HTML5 Canvas 设置顶部/左侧

转载 作者:行者123 更新时间:2023-12-01 01:14:26 26 4
gpt4 key购买 nike

我可以轻松设置 canvas.widthcanvas.height 属性。我找不到正确的 JavaScript 语法来使用顶部和左侧设置 Canvas 的偏移量。我尝试过直接在 Canvas 上和边界矩形上设置这些属性。

我希望能够设置顶部和左侧偏移,以便在用户单击某个点时可以重新定位 Canvas 。

如果canvas.width = 600工作正常;为什么 canvas.top = 80 不起作用?我很困惑。谢谢你的帮助。

最佳答案

为了设置 Canvas 的顶部位置,您需要将 Canvas 包裹在另一个具有绝对定位的div内。然后设置 Canvas 相对于其包装 div 的位置。最后,您可以设置 Canvas 的样式。

确保您提供单位,例如pxemrem% 等...

var panel = document.getElementById('panel');

panel.width = 600;
panel.height = 200;
panel.style.top = '80px'; // Must specify unit.
.container {
position: absolute;
background: #0FF;
}

#panel {
position: relative;
background: #F00;
}
<div class="container">
<canvas id="panel"></canvas>
</div>

docs状态:

The effect of top depends on how the element is positioned (i.e., the value of the position property):

  • When position is set to absolute or fixed, the top property specifies the distance between the element's top edge and the top edge of its containing block. (Containing block needs to have property position: relative)
  • When position is set to relative, the top property specifies the distance the element's top edge is moved below its normal position.
  • When position is set to sticky, the top property behaves like its position is relative when the element is inside the viewport, and like its position is fixed when it is outside.
  • When position is set to static, the top property has no effect.

关于javascript - HTML5 Canvas 设置顶部/左侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54897492/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com