'How to get HTML Canvas from Custom Dialog to Google Spreadsheet
I found a simple scribble pad which uses just <canvas> html, css, and javascript. I create a custom dialog and incorporate the scribble pad into it. That works fine. Now I want to send the image to Google spreadsheet. What I have so far is:
In my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drawing app</title>
<?!= include("CSS_Scribbler"); ?>
</head>
<body>
<section class="container">
<div id="toolbar">
<h1>Draw.</h1>
<label for="stroke">Stroke</label>
<input id="stroke" name='stroke' type="color">
<label for="lineWidth">Line Width</label>
<input id="lineWidth" name='lineWidth' type="number" value="5" min="1" max="10">
<button id="clear">Clear</button>
<button id="submit">Submit</button>
</div>
<div class="drawing-board">
<canvas id="drawing-board"></canvas>
</div>
</section>
<?!= include("JS_Scribbler"); ?>
</body>
</html>
In my <script>:
<script>
const canvas = document.getElementById('drawing-board');
const toolbar = document.getElementById('toolbar');
const ctx = canvas.getContext('2d');
const canvasOffsetX = canvas.offsetLeft;
const canvasOffsetY = canvas.offsetTop;
canvas.width = window.innerWidth - canvasOffsetX;
canvas.height = window.innerHeight - canvasOffsetY;
let isPainting = false;
let lineWidth = 5;
let startX;
let startY;
toolbar.addEventListener('click', e => {
if (e.target.id === 'clear') {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
else if (e.target.id === 'submit') {
try {
var url = canvas.toDataURL("image/jpeg", 1.0);
google.script.run.receiveDataURL(url);
}
catch(err) {
alert(err);
}
}
});
toolbar.addEventListener('change', e => {
if(e.target.id === 'stroke') {
ctx.strokeStyle = e.target.value;
}
if(e.target.id === 'lineWidth') {
lineWidth = e.target.value;
}
});
const draw = (e) => {
if(!isPainting) {
return;
}
ctx.lineWidth = lineWidth;
ctx.lineCap = 'round';
ctx.lineTo(e.clientX - canvasOffsetX, e.clientY);
ctx.stroke();
}
canvas.addEventListener('mousedown', (e) => {
isPainting = true;
startX = e.clientX;
startY = e.clientY;
});
canvas.addEventListener('mouseup', e => {
isPainting = false;
ctx.stroke();
ctx.beginPath();
});
canvas.addEventListener('mousemove', draw);
</script>
In Code.gs:
function receiveDataURL(url) {
try {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName("Sheet1");
sh.insertImage(url,1,1);
}
catch(err) {
console.log(err);
}
}
In my custom dialog this is what I see:
But this is what I get in Spreadsheet:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|


