Creating and saving to file new png image in JavaScript

12,516

Thank you K3N for replying to my question but i did not have time to wrap my head around your answer.

Your answer was just what i needed!

Here is what i got:

var canvas = document.createElement("canvas");

canvas.width = 200;
canvas.height = 200;

var url = canvas.toDataURL();

var a = document.createElement('a');
a.download = 'my.png';
a.href = url;
a.textContent = 'Download PNG';



document.body.appendChild(a);

Share:
12,516
AESTHETICS
Author by

AESTHETICS

Updated on June 04, 2022

Comments

  • AESTHETICS
    AESTHETICS about 2 years

    I am trying to create new empty image with width and height and save it as png to file.

    This is what i got:

    var myImage = new Image(200, 200);
    myImage.src = 'picture.png';
    
    
    window.URL = window.webkitURL || window.URL;
    
    var contentType = 'image/png';
    
    var pngFile = new Blob([myImage], {type: contentType});
    
    var a = document.createElement('a');
    a.download = 'my.png';
    a.href = window.URL.createObjectURL(pngFile);
    a.textContent = 'Download PNG';
    
    a.dataset.downloadurl = [contentType, a.download, a.href].join(':');
    
    document.body.appendChild(a);
    

    I am trying to get transparent image with given width and height in var myImage new Image(200, 200) as the output on the download.