3
\$\begingroup\$

I'm currently in the process of redesigning and coding my website, for which I'm wanting to use paper.js to draw on canvas. Currently the only project page I have is using a basic random ball generator on canvas with paper. I've set up a debounced resize function however the calculations seem to be taking a long time to be applied, which in turn breaks the canvas and the balls appear momentarily out of their containers.

HTML:

    <div class="project-hero cf">
        <canvas id="canvas" resize></canvas>
        <div id="hero-image"></div>
    </div>

JS/Paperscript:

$(document).ready( function() {

    var halfImg = $('.project-image-half'),
        palette = ["#F4E664", "#EF6767", "#2089F8", "#3D9FF8", "#DBDCE0", "#F7F7F7"];

    function canvasSizer() {
        var heroW = $('.project-hero').width(),
            heroH = $('.project-hero').height();

        canvas.width = heroW;
        canvas.height = heroH;

        view.viewSize = new Size(heroW, heroH);
    }

    var imageObj = { 
        heightSizer: function() {

            var imgWidth = halfImg.width();

            halfImg.css({
                height: function() {
                    return imgWidth * 0.716292135 + "px";
                }
            });
        }
    };


    function Ball(r, p) {
        this.path = new Path.Circle({
            fillColor: palette[Math.floor(Math.random()*palette.length)],
            center: p,
            radius: r
        });
    };


    var balls = [];
    var numBalls = 18;
    for (var i = 0; i < numBalls; i++) {
        var position = Point.random() * view.size;
        var radius = Math.random() * 40 + 50;
        balls.push(new Ball(radius, position));
    }


    function init() {
        canvasSizer();
        imageObj.heightSizer();
    }

    function debounce(func, wait, immediate) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    };


    var debouncedFunctions = debounce(function() {
        imageObj.heightSizer();
        canvasSizer();
    }, 50);

    window.addEventListener('resize', debouncedFunctions);

    init();
});

I can't see any reason why it's taking so long. I'm wondering if it's possibly because I'm viewing it on a Retina Display Macbook Pro so the canvas is rendering twice as large?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.