Answer the question
In order to leave comments, you need to log in
Question about recursion in JavaScript
Recently I had to learn a little about drawing with Canvas and JavaScript. Everything was smooth, but I came across one unpleasant (or pleasant) feature of JavaScript'a - the strange behavior of functions during recursion in the presence of local variables.
Consider an example.
function write(x) {
if (x != 0) {
document.write(x);
//х1 = х
write(x-1);
write(x-1);
}
}
function drawall() {
canvas = document.getElementById("canvas");
context = canvas.getContext('2d');
canvas.width = $(document).width(); //Беру размеры документа при помощи jQuery, но можно задать произвольные
canvas.height = $(document).height();
depth = 4;
context.lineWidth = depth;
context.beginPath();
context.moveTo(0,0);
context.lineTo(100,100);
context.stroke();
draw(context, 100, 100, depth-1);
}
function draw(context, x, y, depth) {
if (depth!=0) {
context.lineWidth = depth; // Задаем толщину, которая по ходу будет уменьшаться
context.beginPath();
length = 200;
context.moveTo(x, y);
angle = Math.random()*(Math.PI/2); //Выбираем произвольный угол от 0 до 90 градусов
newx = Math.cos(ugol)*angle+x; //считаем координаты новых точек
newy = Math.sin(ugol)*angle+y;
context.lineTo(newx, newy); // и рисуем до них
context.stroke();
draw(context, newx, newy, depth-1); //И продолжаем наше дело :)
draw(context, newx, newy, depth-1);
draw(context, newx, newy, depth-1);
}
}
Answer the question
In order to leave comments, you need to log in
Firstly, in the first example, you have the Russian letter “x” in the commented line, so after the first start of write everything breaks. If you write a normal x, the result will be normal.
Second, local variables need to be defined as "var x1=x;" and what you have now is the global variable x1 (also known as window.x1). Read about JS scopes.
draw(context, newx, newy, depth-1); //И продолжаем наше дело :)
draw(context, newx, newy, depth-1);
draw(context, newx, newy, depth-1);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question