paper.js how to set up multiple canvases using only javascript

后端 未结 6 804
予麋鹿
予麋鹿 2021-02-13 21:31

I\'m trying to use paper.js in a webapp, but I\'ve been unable to get it to work with multiple canvases. It\'s like the scopes are getting mixed up between the canvases, so when

6条回答
  •  无人及你
    2021-02-13 22:35

    I think I found the solution: I expanded the fiddle from @freejosh to also work with callbacks (e.g. resize): The trick is to re-fetch the correct scope inside the callback function:

    http://jsfiddle.net/rassoh/mx9n3vsf/7/

    var mypapers = [];
    
    initPaper(0, $("#canvas1")[0]);
    initPaper(1, $("#canvas2")[0]);
    
    function initPaper(id, canvasElement) {
        var mousePosition = new paper.Point(0,0);
        mypapers[id] = new paper.PaperScope();
        paper = mypapers[id];
        paper.setup(canvasElement);
        var myCircle;
    
        createCircle = function() {
            if( "undefined" !== typeof myCircle) {
                myCircle.remove();
            }
            // this function is called on resize, so we have to re-fetch the scope!
            paper = mypapers[id];
            myCircle = new paper.Path.Circle(30, 30, 20);
            var lightRed = new paper.Color(1, 0.5, 0.5);
            var lightBlue = new paper.Color(0.5, 0.5, 1);
            myCircle.style = {
                fillColor: id === 0 ? lightRed : lightBlue,
                strokeColor: "black"
            };
        }
        createCircle();
    
        var tool = new paper.Tool();
        tool.onMouseMove = function(event) {
            mousePosition = event.lastPoint;
        };
        paper.view.onFrame = function() {
            if( "undefined" === typeof myCircle) {
                return;
            }
            var dist = mousePosition.subtract( myCircle.position );
            dist = dist.divide( 3 );
            myCircle.position = myCircle.position.add( dist );
        };
        paper.view.onResize = function() {
            createCircle();
        };
    }
    
    $(window).resize(function() {
        var width = $(".container").width() / 2;
        var height = $(".container").height();
        // this automatically triggeres paper's onResize event registered above
        mypapers[0].view.viewSize = new paper.Size( width, height );
        mypapers[1].view.viewSize = new paper.Size( width, height );
    });
    

    Please note that I also included a simple interaction with the circles, to also test for correct behaviour there.

提交回复
热议问题