R
R
Ragtime Kitty2019-06-07 16:14:38
JavaScript
Ragtime Kitty, 2019-06-07 16:14:38

How to draw a polyline in canvas?

Hello.
Can you please tell me how to draw a broken line from point A to point B through canvas?
Something like this:
5cfa60432bd4a310152629.png
I.e. bending through every random number of pixels, with an alternating side (plus/minus sign) and a random deviation.
I tried to do it through several lines, each time moving the coordinates and adding a random number, but it turns out some kind of broom :(
I don’t know how to do math, if you can, please explain using your fingers or better with an example.
Thank you ♥

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
twobomb, 2019-06-07
@Ragtime_Kitty

Here is an example demo I wrote .
Well the basic functions

/// (начальный х, начальный у,конечный х,конечный у, минимальная длина линии,макс длинная линии, минимальная угол отклонения, макс угол отклонение) вернет массив точек
function generateLines(xStart,yStart,xEnd,yEnd, lenRandMin,lenRandMax,angleDeviationMin, angleDeviationMax ){
  var arrayPos = ;
  var xCur = xStart;
  var yCur = yStart;
  angleDeviationMin = (angleDeviationMin * Math.PI)/180;//в радианы
  angleDeviationMax = (angleDeviationMax * Math.PI)/180;//в радианы
  
  var deviationPos = false;
  do{
  	if(getDist(xCur,yCur,xEnd,yEnd) <= lenRandMax){
      xCur = xEnd;
      yCur = yEnd;
    }
    else{
    	var len = rand(lenRandMin,lenRandMax);
      var angle = getAngle(xCur,yCur,xEnd,yEnd) + (deviationPos?rand(angleDeviationMin,angleDeviationMax):-rand(angleDeviationMin,angleDeviationMax));
    	xCur += Math.cos(angle) * len;
      yCur += Math.sin(angle) * len;
    }
    arrayPos.push([xCur,yCur]);
    deviationPos = !deviationPos;
  }while(!(xCur == xEnd && yCur == yEnd));
  return arrayPos;
}
//Получить угол между двумя точками
function getAngle(dx,dy,dx1,dy1){
  return Math.atan2(dy - dy1,dx - dx1) + Math.PI;
}
///Получить растояние между двумя точками
     function getDist(x,y,x1,y1){
         return Math.sqrt(Math.pow(x1 - x,2)+Math.pow(y1-y,2));
     }
//Получить рандомное от min до max
function rand(min, max) {
  return min + Math.random() * (max - min)
}

H
hzzzzl, 2019-06-07
@hzzzzl

fill the broom on https://codepen.io, we will try :)

I
i1yas, 2019-06-07
@i1yas

A crooked way, but still:
Go from two points towards, when the distance between the lines reaches a certain threshold value, close these lines. Demo

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question