Search code examples
javascriptmongodbpaperjs

PaperJS variables, how can I store these in MongoDB?


I'm learning to code and have created a project using PaperJS.

I have a function which updates the total score, and displays it on top of the page.

function updateScore(){
  text.content = 'Circles Cleared: ' + total;
  text.bringToFront();
}

Total is my variable holding the current score. I'm struggling to use this anywhere else in my code / post it to MongoDB because it appears that the variable isn't global? I've written inline paperscript in the HTML file.

I've tried appending the total to a form, and submitting the form by making a POST call, but it keeps returning as total is undefined.

Even in console.logging the total is not appearing after completing the POST call.

Any help is appreciated, thanks in advance.


Solution

  • Your main problem is that PaperScript code is executed in a different scope as your JavaScript code.
    In order to share variables between both, the easiest way is to use Paper.js directly in JavaScript (see documentation).
    Here is a simplified working example of the case you describe (total is displayed through Paper.js in the canvas).

    // setup paperjs
    paper.setup(document.getElementById('canvas'));
    
    // init total variable
    var total = 0;
    
    // init total text item
    var totalText = new paper.PointText({
      point: paper.view.center,
      justification: 'center'
    });
    
    displayTotal();
    
    // listen to button click
    $('button').click(function() {
      // increment total variable
      total += 100;
      // display total
      displayTotal();
    });
    
    function displayTotal() {
      totalText.content = 'total = ' + total;
    }
    html,
    body {
      margin: 0;
      overflow: hidden;
      height: 100%;
    }
    
    canvas[resize] {
      width: 100%;
      height: 100%;
    }
    
    button {
      position: fixed;
      top: 15px;
      left: 15px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.11.5/paper-core.min.js"></script>
    
    <canvas id="canvas" resize></canvas>
    <button>increment total</button>