gpt4 book ai didi

javascript - 根据外部高度值移动 Canvas (线)

转载 作者:行者123 更新时间:2023-12-03 12:12:04 24 4
gpt4 key购买 nike

我使用 Canvas 创建了一个正方形和一条线。

这是代码

<canvas id="c4" width="200px" height="150px"></canvas>
<div>
<canvas id="square" width="200px" height="150px"></canvas>
</div>

这是 fiddle 链接。

Fiddle

我想要的是动态地移动方形 Canvas 底部的水平线。

enter image description here

我现在根据我需要在正方形底部设置水平线的外部高度获得了正方形的外部高度。

提前致谢中号

最佳答案

该线永远不会位于矩形内部,因为 2 个 Canvas 元素不重叠。

http://jsfiddle.net/m1erickson/yg9R8/

enter image description here

您可以使用 Html + CSS 使 Canvas 重叠,然后更改线条坐标,使其根据需要对齐。

Html:将两个 Canvas 包裹在一个 div 中

<div id=wrapper>
<canvas id="c4" width="200px" height="150px"></canvas>
<canvas id="square" width="200px" height="150px"></canvas>
</div>

CSS:使 2 个 Canvas 重叠

#wrapper{position:relative;}
canvas{position:absolute;}
#c4{z-index:5}

JavaScript绘制直线和矩形

var c=document.getElementById("square");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.stroke();
ctx.fillStyle ="#f2f2f2";
ctx.fill();


var c4 = document.getElementById("c4");
var c4_context = c4.getContext("2d");
c4_context.beginPath();
c4_context.moveTo(20, 120);
c4_context.lineTo(300, 120);
c4_context.strokeStyle = "Green";
c4_context.stroke();

关于javascript - 根据外部高度值移动 Canvas (线),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24919680/

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