我正在使用setInterval调用对HTML5画布上的分形进行动画处理的函数。还有一个滑块,允许用户更改分形的质量。一切正常,直到我开始更换滑块。当我更改它时,分形动画变得断断续续,最终“ drawFractal”函数停止调用。
这是滑块HTML:

<input type="range" id="qualitySlider" min="1" max="10"></input>


这是javascript(它只会生成一个分形):

var count = 0.5;

var slider = document.getElementById("qualitySlider");
var g = document.getElementById("drawingCanvas").getContext("2d");

function drawFractal() {
    var cellSize = Math.ceil(slider.value);
    //canvas is 700 by 400
    g.fillStyle = "black";
    g.clearRect(0, 0, 700, 400);

    //Eveything from here to the end of this function generates the fractal
    var imagC = Math.cos(count)*0.8;
    var realC = Math.sin(count)*0.5;
    for (x = 0; x < 700; x+=cellSize) {
        for (y = 0; y < 400; y+=cellSize) {
            var yCoord = (x / 700.0 - 0.5)*3;
            var xCoord = (y / 400.0 - 0.5)*3;
            var real = xCoord;
            var imag = yCoord;

            var broken = 0;
            for (i = 0; i < 8; i++) {
                var temp = real*real - imag*imag + realC;
                imag = 2*imag*real + imagC;
                real = temp;
                if (real*real + imag*imag >= 4) {
                    broken = true;
                    break;
                }
            }

            if (!broken) {
                g.fillRect(x, y, cellSize, cellSize);
            }
        }
    }
    count = count + 0.04;
}

setInterval(drawFractal, 60);


我只需要每60毫秒可靠地调用一次“ drawFractal”函数即可。

最佳答案

这是我改进的代码。我只是使用requestAnimationFrame递归调用“ drawFractal”函数。我还使用setTimeout函数将动画限制为24帧/秒。

var count = 0.5;

var qualitySlider = document.getElementById("qualitySlider");
var g = document.getElementById("drawingCanvas").getContext("2d");

function drawFractal() {
    var cellSize = Math.ceil(qualitySlider.value);
    //canvas is 700 by 400
    g.fillStyle = "black";
    g.clearRect(0, 0, 700, 400);
    var imagC = Math.cos(count)*0.8;
    var realC = Math.sin(count)*0.5;
    for (x = 0; x < 700; x+=cellSize) {
        for (y = 0; y < 400; y+=cellSize) {
            var yCoord = (x / 700.0 - 0.5)*3;
            var xCoord = (y / 400.0 - 0.5)*3;
            var real = xCoord;
            var imag = yCoord;

            var broken = 0;
            for (i = 0; i < 8; i++) {
                var temp = real*real - imag*imag + realC;
                imag = 2*imag*real + imagC;
                real = temp;
                if (real*real + imag*imag >= 4) {
                    broken = true;
                    break;
                }
            }

            if (!broken) {
                g.fillRect(x, y, cellSize, cellSize);
            }
        }
    }
    count = count + 0.04;
    setTimeout(function() {
        requestAnimationFrame(drawFractal);
    }, 41);
}

drawFractal();

10-07 13:46