How would I reference a specific Google Sheets cell using the p5.js library in GAS

Viewed 82

I'm trying to use GAS to do generative art based on values in a google sheet (that theoretically, I can update and have the script change the art). However, I'm running into an issue with how to reference the contents of a specific cell in my script, specifically in the draw function for the p5.js library, which I am referencing in the html file.

Here's my current code

const MAX_HEIGHT = 600;
const MAX_WIDTH = 600;
const STEP = 16;

function setup(){
  createCanvas(MAX_HEIGHT, MAX_WIDTH);
  stroke(169, 251, 215);
  background('grey');
  strokeWeight(2);
  noLoop();
  var numb;
  var add;
  var val = SpreadsheetApp.openById("1CLdlLWU8RwkYaRj6rpE7avxRCODmNh9fxLqADEGQ22k").getSheetByName("Sheet3").getRange("A1:A1");
  var x = val.getValue();

}

function draw(){  
  let numb = 30;
  let add = numb + 70;
  triangle(x, 250, add, 190, numb, 50);
  }
<!DOCTYPE html>
<html>
    <head>
        <title>P5.js Example</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.14/p5.js"></script>
        <script src="sketch.gs"></script>
    </head>
    <body>
    </body>
</html>

And here is my doGet function:

function doGet() {
   var template = HtmlService.createTemplateFromFile("index.html");
   return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME); 
}

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
      .getContent();
}

Can somebody explain to me what I'm doing wrong? The debug console keeps finding both var and x as undefined, and I can't figure out why.

1 Answers

Try this:

js:

</script>
const MAX_HEIGHT = 600;
const MAX_WIDTH = 600;
const STEP = 16;
var x;
function setup() {
  createCanvas(MAX_HEIGHT, MAX_WIDTH);
  stroke(169, 251, 215);
  background('grey');
  strokeWeight(2);
  noLoop();
  var numb;
  var add;
  google.script.return
  .withSuccessHandler(v => x=v;)
  .getXValue();
}
</script>

gs:

function getXValue() {
  return SpreadsheetApp.getActive().getSheetByName("Sheet3").getRange("A1").getValue();
}

Be careful doing anything immediately following the function because it will take some time between issuing the command and having it complete.

Related