JSFiddle - React, Tailwind, and code Playground

by rassoh

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.9.22/paper-full.min.js"></script>
<p>The light red circle should be in the red square, and the light blue circle should be in the blue square. Move your Mouse over the squares for testing interaction. Resize your browser to test correct behaviuor for callbacks :)</p>
<div class="container">
    <canvas id="canvas1"></canvas>
    <canvas id="canvas2"></canvas>
</div>

CSS

.container {
    position: relative;
    outline: 1px solid;
    height: 200px;
    width: 100%;
}
canvas {
    display: block;
    position: absolute;
    top: 0;
    width: 50%;
    height: 100%;
}

#canvas1 {
    left: 0;
    background-color: red;
}
#canvas2 {
    left: 50%;
    background-color: blue;
}

JavaScript

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 );
});