Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    };
like image 494
Mark Kortink Avatar asked Dec 03 '25 12:12

Mark Kortink


1 Answers

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.

like image 188
Kesavamoorthi Avatar answered Dec 06 '25 03:12

Kesavamoorthi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!