Mor*_*n J 4 html5 canvas html5-canvas
我想画这样的折线

从一组角度和长度组成的数组(50和100,90和20,90和30等..)
有任何想法吗?
这是一个艰难的...
例如角度和长度的对象数组:
var arr = [
{ angle: 0, h: 50 },
{ angle: 90, h: 60 },
{ angle: 180, h: 70 },
{ angle: 270, h: 80 },
{ angle: 180, h: 90 }
];
Run Code Online (Sandbox Code Playgroud)
以下绘制方法将绘制前一个数组中的行,
function getAngle(ctx, x, y, angle, h) {
var radians = angle * (Math.PI / 180);
return { x: x + h * Math.cos(radians), y: y + h * Math.sin(radians) };
}
function draw() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.beginPath();
var pos = { x: 400, y: 400 };
for (var i = 0; i < arr.length; i++) {
ctx.moveTo(pos.x, pos.y);
pos = getAngle(ctx, pos.x, pos.y, arr[i].angle, arr[i].h);
ctx.lineTo(pos.x, pos.y);
}
ctx.stroke();
}
}
Run Code Online (Sandbox Code Playgroud)
你可以在canvas元素之后调用draw
<div style="width:800px;height:800px;border:solid 1px red;">
<canvas id="canvas" width="800" height="800"></canvas>
</div>
<script type="text/javascript">
draw();
</script>
Run Code Online (Sandbox Code Playgroud)
编辑:尝试更改绘图功能,
function draw() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.beginPath();
var pos = { x: 400, y: 400 },
angle = 0;
for (var i = 0; i < arr.length; i++) {
angle += arr[i].angle;
angle = (arr[i].angle + angle) % 360;
ctx.moveTo(pos.x, pos.y);
pos = getAngle(ctx, pos.x, pos.y, arr[i].angle + angle, arr[i].h);
ctx.lineTo(pos.x, pos.y);
}
ctx.stroke();
}
}
Run Code Online (Sandbox Code Playgroud)