0

I copied the code for this link: http://jamesbaca.net/slides/source_code/html5_andJSThumbs/ . The demo runs fine on the server, but my local code yields no image. I ran Inspect element for the demo & my own copy. The demo shows a src for the image element. The copy shows only the original code. Where did the src come from, & how do I get the copy to render the same result as the original demo?

JimM
  • 111
  • 1
  • 11
  • 1
    Are you trying to load it as a file:// URL? – aldel Nov 08 '14 at 18:49
  • [duplicate question?](http://stackoverflow.com/questions/22710627/tainted-canvases-may-not-be-exported) – aldel Nov 08 '14 at 18:58
  • @aldel Trying to display it as a simple data URL to be saved by a right click. Apparently, image conversion to base64 is done with external online services. Can one insert local code to do the task? – JimM Nov 08 '14 at 21:31
  • I'm not sure what you mean by "external online services". – aldel Nov 09 '14 at 22:58
  • 1
    I suspect you're trying to run the code from your local drive, using "open file" or a file:// URL, which would fail because of security restrictions (see the other question I linked, and the canvas 2D context specs). But it's hard to tell because you didn't say whether that's what you tried to do. – aldel Nov 09 '14 at 23:00
  • @aldel The call to the image src is img.setAttribute('src', dataURL); I meant a server/client connection in which the server sets the attribute for the dataURL, if I'm interpreting it right. I'm puzzled by that, so it might be the crux of my question. You're correct about the security issue. Can the image attribute be set locally? – JimM Nov 10 '14 at 13:52
  • @aldel Sorry. I didn't really answer your question about loading the file. It would be file:// URL. I'm opening the file from my javascript compiler or the saved file from File Explorer with Open with... Chrome or IE. – JimM Nov 10 '14 at 14:03
  • @aldel Hope I'm not spamming your inbox with comments. Thank you for your patience. Your questions led me to what appears to be the solution. Is this the line of code for which I was searching? var dataURL = canvas.toDataURL(); Please reply with an answer instead of a comment. – JimM Nov 10 '14 at 15:23

1 Answers1

0

The problem is not in your code; that's why it works on the server. It fails only because you're trying to load it from a file instead of a server. An image from a file:// URL automatically "taints" the canvas (even if it's loaded by a page that is also a file:// URL), which means that calling toDataURL will throw an error:

If the canvas element's bitmap's origin-clean flag is set to false, throw a SecurityError exception and abort these steps.

You should instead run a local server and load your code from that. For example, assuming you have Python installed, you can cd to the directory your files are in and run:

python -m SimpleHTTPServer 8009

Then point your browser to http://localhost:8009/yourfile.html

aldel
  • 6,489
  • 1
  • 27
  • 32