DEV Community

So Sun Park
So Sun Park

Posted on

canvas to image HTML, javascript

save canvas to image and then show on your div

  1. create empty Image() object
  2. convert canvas to DataURL image file
  3. create HTML element for img
  4. Inject imageURI to new HTML element source
  5. append your HTML element to document.
  6. Inject imageURI to your Image() object source
let myImage = new Image();
let imageURI = this.myCanvas.toDataURL("image/png");

let newImageElement = document.createElement('img');
newImageElement.setAttribute("id", "new-image");
newImageElement.src = imageURI;
document.body.appendChild(newImageElement);
this.myImage.src = imageURI;
Enter fullscreen mode Exit fullscreen mode

funny thing I found.

image/jpg, image/png: saves transparent background
image/jpeg: saves transparent area as black color

Blob instead of dataURL

Top comments (0)