Draw a series of rotated lines using an HTML canvas

I want to draw such a polyline

enter image description here

from an array consisting of sets of angles and lengths (50 and 100, 90 and 20, 90 and 30, etc.)

Any ideas?

+4
source share
2 answers

It was hard ...

for example, an array of angle and length objects:

var arr = [ { angle: 0, h: 50 }, { angle: 90, h: 60 }, { angle: 180, h: 70 }, { angle: 270, h: 80 }, { angle: 180, h: 90 } ]; 

the next drawing method will draw lines from the previous array,

 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(); } } 

you can call a draw after the canvas element

 <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> 

EDIT: try changing the drawing function to this,

 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(); } } 
+6
source

I had a similar problem with Morten and I tried the second function of the Shlomi Comemi draw and it works fine ... but only for the Array, which he gave only with a multiple of 90 Β°. However, if you try 30 Β°, you will notice that something is wrong, because the right corner is drawn. I realized that the reason for this is that the angle and arr [i] .angle add up 3 times. Here is the corrected version of the function:

 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) % 360; ctx.moveTo(pos.x, pos.y); pos = getAngle(ctx, pos.x, pos.y, angle, arr[i].h); ctx.lineTo(pos.x, pos.y); } ctx.stroke(); } } 

This should work (but I think Morten doesn't care about three years ...).

0
source

Source: https://habr.com/ru/post/1385246/


All Articles