0

I have an HTML button that captures the canvas image using toDataURL(). I want to pass the data to a form element, which will send via formmail. I can get all other variables passed via hidden form elements, but the canvas data won't take. It must not be formatted properly to send. What is the correct syntax to send, if possible?

In JavaScript

imgData = theCanvas.toDataURL();

document.getElementById('theImageData').value=imgData;

In HTML

<input type="hidden" name="theImageData" id="theImageData" value="">
MartyIX
  • 27,828
  • 29
  • 136
  • 207
bobcodenewbie
  • 53
  • 1
  • 8
  • Your code sample seems to be correct. You should use `console.log(imgData)` to see what data you put in `imgData` variable. – MartyIX Nov 14 '15 at 18:52
  • https://github.com/operasoftware/shinydemos/blob/master/demos/photo-booth/scripts/photobooth.js#L152 – markE Nov 14 '15 at 18:58
  • @Martin Vseticka document.getElementById('theImageData').value=imgData.value; seemed to work instead. I forgot to ask about the second part. I opened a blank JS with an empty variable and pasted the captured data into the variable's value. When I let it run with: context.putImageData(imgData, 0, 0); it didn't draw anything in the canvas. Any tips? – bobcodenewbie Nov 14 '15 at 20:21
  • https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL `imgData.value` should not work. That's very strange to me. To answer your second question: you should use this approach when you have data URL http://stackoverflow.com/a/3379955/99256 – MartyIX Nov 14 '15 at 20:47

1 Answers1

0

When you use:

var imgData = theCanvas.toDataURL(); 

imgData should be then a string containing something like this data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby...

this format is suitable for transfering in an HTML form (as opposed to some binary data).

To use imgData to put it back somewhere on the canvas, you can use this:

var img = new Image();
img.src = imgData;
var ctx = theCanvas.getContext('2d');
img.onload = function() {
  ctx.drawImage(img, 0, 0);
  img.style.display = 'none';
};
MartyIX
  • 27,828
  • 29
  • 136
  • 207
  • Worked great when I pasted generated data directly into a variable declaration and ran the JS, however when I SENT the canvas data via formmail and copied the canvas data from my email into a JS variable declaration, and ran the JS, it wouldn't work. I kept getting "unexpected token :" I had surrounded the var value with quotes and ended with a semicolon, which DID work the first time, something's getting lost when it goes through email? – bobcodenewbie Nov 14 '15 at 22:42
  • In this specific case, it should be OK as you did it. Something must happen to data along the way. – MartyIX Nov 14 '15 at 22:47
  • Yes, it formatted the email text with extra returns every 3 lines, but a little scanning and editing makes it work! Onward and upward. – bobcodenewbie Nov 14 '15 at 23:47