简体   繁体   中英

Can not clear the fabric canvas

I am relatively new to Fabric and also JavaScript. I have written a simple book application, and when a user moves to the next page I need to clear the canvas so a function can draw the next page. For some pages no matter what I do I cannot get the canvas to clear. I have tried using canvas.clear() and going through the back door and using context.clearRect, both inside and outside the function. The following code is based on the "Sliding Ladybirds" demo on fabricjs.com, notice the last line of the function should clear the canvas, but it doesn't, neither do the other options mentioned above. Can anyone tell me what I am missing?

    window.onload = function () {
        function pics() {
            var canvas = this.__canvas = new fabric.Canvas('cvs', { selection: false });
            fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center';

            setInterval(function () {
                fabric.Image.fromURL('http://fabricjs.com/assets/ladybug.png', function (img) {
                    img.set('left', fabric.util.getRandomInt(200, 600)).set('top', -50);
                    img.movingLeft = !!Math.round(Math.random());
                    canvas.add(img);
                });
            }, 1000);

            (function animate() {
                canvas.forEachObject(function (obj) {
                    obj.left += (obj.movingLeft ? -1 : 1);
                    obj.top += 1;
                    if (obj.left > 900 || obj.top > 500) {
                        canvas.remove(obj);
                    }
                    else {
                        obj.setAngle(obj.getAngle() + 2);
                    }
                });
                canvas.renderAll();
                fabric.util.requestAnimFrame(animate);
            })();
            canvas.clear();
        };
        pics();
    };

If you have a closer look at the code, It has a setInterval() method which will be called continuously for every second (1000 millisecond). You are using the canvas.clear() method outside the setInterval() . So even though you clear the canvas, images will be added when the setInterval() get executed for the next time. Either you can use clearInterval() method to clear the setInterval() when clearing the canvas (recommended) or place the canvas.clear() inside setInterval() based on your need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM