I'm trying to get an HTML canvas into Google Spreadsheet. I found a simple scribble pad which uses just html, css, and javascript. I create a custom dialog and incorporate the scribble pad into it. That works fine. Now I want to send to Google spread sheet. What I have so far is:
In my HTML:
<canvas id="drawing-board"></canvas>
In my <script>
:
const canvas = document.getElementById('drawing-board');
var url = canvas.toDataURL("image/jpeg", 1.0);
google.script.run.receiveDataURL(url);
In Code.gs:
function receiveDataURL(url) {
try {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName("Sheet2");
var blob = Utilities.newBlob(Utilities.base64Decode(url), 'image/jpg', 'MyImageName');
sh.insertImage(blob,1,1);
}
catch(err) {
console.log(err);
}
}
If I just insertImage(url,'image/jpg') I get a black box. It should be white with some scribble on it.
Any ideas?
CodePudding user response:
I have not tested this...
Instead of
Utilities.base64Decode(url)
tryUtilities.base64Decode(url.splice(',').slice(-1))
. This because toDataUrl returns a string of the form"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"
Instead of
toDataURL
trytoBlob
( you will have to adapt your server-side code to receive a blob instead of a string). This because toBlob returns a blob instead of aDOMString
.
Resources
- https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL
- https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob
CodePudding user response:
As another answer, the method of "insertImage" can directly use the data URL. So your script can be modified as follows.
Modified script:
function receiveDataURL(url) {
try {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName("Sheet2");
sh.insertImage(url,1,1);
}
catch(err) {
console.log(err);
}
}
As a sample HTML&Javascript, you can test this using the following Javascript.
<canvas id="drawing-board"></canvas> <script> const canvas = document.getElementById('drawing-board'); canvas.width = 100; canvas.height = 50; // Sample rectangle image is put. const context = canvas.getContext("2d"); context.beginPath(); context.rect(0, 0, 100, 50); context.fillStyle = "#FF0000"; context.fill(); // Retrieve the data URL. var url = canvas.toDataURL("image/jpeg", 1.0); google.script.run.receiveDataURL(url); </script>
- When this script is run, a red rectangle is put to "Sheet2".