'Get image from offscreen canvas

I am trying to draw graphics off screen and transfer to Google Sheet. I've been able to do it on screen with toDataUrl(). I have attached a screen shot of JSON trace to show the data is getting returned properly.

I found the problem. trace.size is reversed. I've corrected the mistake below. The problem was I was trying to draw off canvas. Notice that canvas is still off screen but within the sidebar HTML Script.

HTML

<script>
  function sheetsOnChange() {
    var sheet = document.getElementById("sheets").value;
    google.script.run.withSuccessHandler(
      function (trace) {
        try {
          alert(trace);
          trace = JSON.parse(trace);
          const canvas = document.createElement("canvas");
          canvas.width = trace.size[1];
          canvas.height = trace.size[0];
          const ctx = canvas.getContext('2d');
          ctx.beginPath();
          ctx.moveTo(0,0);
          ctx.lineTo(canvas.width,canvas.height);
          ctx.stroke();
          var url = canvas.toDataURL("image/png", 1.0);
          google.script.run.receiveDataURL(url);
        }
        catch(err) {
          alert(err);
        }
      }
    ).getTrace(sheet);
  }
</script>

Code.gs

function receiveDataURL(url) {
  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sh = ss.getActiveSheet();
    sh.insertImage(url,1,1);
  }
  catch(err) {
    console.log(err);
  }
}

Trace

enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source