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=""> 
4
  • Your code sample seems to be correct. You should use console.log(imgData) to see what data you put in imgData variable. Commented Nov 14, 2015 at 18:52
  • github.com/operasoftware/shinydemos/blob/master/demos/… Commented Nov 14, 2015 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? Commented Nov 14, 2015 at 20:21
  • developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/… 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 stackoverflow.com/a/3379955/99256 Commented Nov 14, 2015 at 20:47

1 Answer 1

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'; }; 
Sign up to request clarification or add additional context in comments.

3 Comments

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?
In this specific case, it should be OK as you did it. Something must happen to data along the way.
Yes, it formatted the email text with extra returns every 3 lines, but a little scanning and editing makes it work! Onward and upward.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.