Answer the question
In order to leave comments, you need to log in
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:
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
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)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question