0

First, I'd like to say that I have been looking for the answer for hours...

The problem is the following. I have a canvas in my HTML code which displays at the screen some drawings. What I want to do is to transform what I can see on my screen (in the canvas) into an image, which would be displayed in a "img" tag like classic images in websites.

In my HTML code, I have :

<canvas height="842" width="595"></canvas>

And when I look at the screen, I have indeed something.

But what I want in my code is something like that:

<img src="blabla" style="height: 842px; width: 595px";></img>

And the line above would be supposed to display an image which is identical to what we can see in the canvas.

Here is a part of my javaScript code. The canvas variable is something that has been already created before and this is what displays what is in my canvas, so it works.

var image = new Image();
image.src = canvas.toDataURL("image/jpg");

image.style.height = canvas.height;
image.style.width = canvas.width;

document.body.appendChild(image);

When I run my code and when I open DevTools, in my HTML code, there is the line, with an URL in the src tag. But visually, on my screen, there is nothing. The image is not even white, there is absolutely nothing. In DevTools, when I hover the line of the image, I can see that there is a place reserved to my image with the good dimensions, but there is nothing inside. The console doesn't detect any error.

What should I do ?

A L
  • 1
  • 1
  • It works on [jsfiddle](https://jsfiddle.net/2ow56skj/), create a snippet to show us the result you get. Or put a complete code and html here. – fuyushimoya Aug 03 '15 at 15:11
  • possible duplicate of [How To Save Canvas As An Image With canvas.toDataURL()?](http://stackoverflow.com/questions/10673122/how-to-save-canvas-as-an-image-with-canvas-todataurl) – Jamie Barker Aug 03 '15 at 15:17
  • Your code looks OK. Make sure you host the image is hosted on the same domain as the web page or else you'll violate cross-origin restrictions (CORS). Violating CORS will taint your canvas which will automatically cause `.toDataURL` to be disallowed. – markE Aug 03 '15 at 15:43

1 Answers1

0

I've copy/paste you code and it works like a charm. http://jsbin.com/hojuco/edit?html,css,js,output

Do you draw something in you canvas before export it ? Canvas are transparent on start so be sure it's not just empty.

Otherwise, you mixed up your variable.

GMartigny
  • 126
  • 8