【发布时间】:2012-01-01 14:47:01
【问题描述】:
这不是 HTML、CANVAS 问题,而是一般数学问题。我在这里发布它是因为它是使用 CANVAS 进行原型设计的,并且仍然是我认为有人可以回答的一般编程问题。这是基本思想:我想画一条 10 像素粗的线,但我不想使用标准 lineTo 并设置笔画宽度。我想实际使用 beginPath 和 lineTo 绘制线条的边框。原因是这实际上是针对 AS3 项目的,使用这种方法可以让我们进行线条描边和填充。所以旋转画布和那种性质的东西是不可能的。我只需要弄清楚如何计算直线的正确 x、y 坐标。
在下面的代码中是行首的坐标。我基本上想取这个坐标,为每个坐标添加 10 到 y 轴,这将为我提供线底部的返回坐标。当然,线的每一段都是旋转的,因此计算线底部的坐标被证明是很棘手的。我希望有人可以提供帮助。
运行示例代码后,问题应该很明显。线没有正确绘制。对于线段的相对温和的旋转,它似乎可以工作,但随着旋转角度变得更严重,x、y 坐标的计算不正确。
<!doctype html>
<html>
<body>
<canvas id="canvas" width="800" height="600">
</canvas>
<script type="text/javascript">
var coords = [
{x:78,y:183},
{x:130,y:183},
{x:237,y:212},
{x:450,y:213},
{x:517,y:25},
{x:664,y:212},
{x:716,y:212}
];
var coordsBck = [];
for( i = 0; i < coords.length; i++ ) {
var c1, c2, r;
c1 = coords[i];
if( i < coords.length - 1 ) {
c2 = coords[i + 1];
r = Math.atan2((c2.y - c1.y),(c2.x - c1.x));
console.log( c1.x, c1.y, c2.x, c2.y, ( r * 180/Math.PI ));
}
else
{
r = 00;
}
var d = r * 180/Math.PI;
var cos = Math.cos( r );
var sin = Math.sin( r );
var x = cos * 0 - sin * 10;
var y = sin * 0 + cos * 10;
coordsBck.push({x: c1.x + x, y: c1.y + y});
}
while(coordsBck.length > 0 )
{
coords.push( coordsBck.pop() );
}
var ctx = document.getElementById("canvas").getContext("2d");
ctx.beginPath();
for( i = 0; i < coords.length; i++ ) {
var line = coords[i];
console.log( i, line.x, line.y );
if( i == 0 )
{
ctx.moveTo( line.x, line.y );
}
else
{
ctx.lineTo( line.x, line.y );
}
}
ctx.fill();
function t(o) {
return "x: " + o.x + ", y: " + o.y;
}
</script>
</body>
</html>
【问题讨论】:
标签: javascript math canvas trigonometry