janpaul123 / paperprograms

Run Javascript on pieces of paper!
https://paperprograms.org
MIT License
502 stars 54 forks source link

Return cached canvas instead of null when requesting canvas multiple times #66

Closed paulsonnentag closed 6 years ago

paulsonnentag commented 6 years ago

This pull request adds caching for canvas get requests. This simplifies cases where we want to request the canvas dynamically. For example when the program draws something on a paper placed at the whisker.

Example:

const whisker = await paper.get('whisker', { direction: 'up' });

var canvas;
var ctx;

whisker.on('paperAdded', ({paperNumber}) => {
   // without the caching this would work only once 
  // each subsequent request would return null  instead of the canvas
   canvas = paper.get('canvas', { number: paperNumber }) 
   ctx = canvas.getContext('2d')
})

whisker.on('paperRemoved', () => {
  canvas = null;
  ctx = null;
});

setInterval(async () => {
    if (canvas) {
     // draw something on other canvas
    }
})