space-2d icon indicating copy to clipboard operation
space-2d copied to clipboard

Download canvas image onclick

Open zorker opened this issue 8 years ago • 4 comments

Not really an issue. But not sure where else I could write this.

I wanted to use your script to create space wallpapers for myself.

Since the canvas context is webgl I needed to preserve the drawing buffer. Otherwise the canvas blob will be blank.

//addition to the canvas settings in bundle.js
var canvas = document.getElementById('render-canvas');
var glContextAttributes = { preserveDrawingBuffer: true };
var gl = canvas.getContext("experimental-webgl", glContextAttributes);
canvas.width = 2560; //window.innerWidth - (300 + 16 + 16 + 16);
canvas.height = 1440; //window.innerHeight - (16 + 16);

I rerender the image by reloading the browser. Maybe you find a better solution that makes the preserveDrawingBuffer work with the gui redraw.

//download img as png on canvas click
  (function() {
    var canvas = document.querySelector("#render-canvas");
    var uri;
    canvas.onclick = function(evt) {
      evt.preventDefault();
      canvas.toBlob(function(blob) {
        if(uri)
          (window.URL||window.webkitURL).revokeObjectURL(uri);
        uri = (window.URL||window.webkitURL).createObjectURL(blob);
        var a = document.createElement('a');
        a.href = uri;
        a.download="stars.png";
        document.body.appendChild(a);
        a.onclick = function(evt) { this.parentNode.removeChild(this); }
        a.click();
      });
    }
  })();

zorker avatar Oct 25 '16 10:10 zorker

Hi @zorker - most browsers will let you right click -> save image. Does this not work for your use case?

wwwtyro avatar Oct 26 '16 00:10 wwwtyro

Yes that should be alright aswell if the drawingBuffer contains data.

zorker avatar Oct 26 '16 07:10 zorker

Yo, I'd like to bump on that. There is currently no way to save the generated image other than taking a screenshot. Given that I'd like to generate a 10k*3k pixels image, that's not a solution for me. I'll try to use zorker's code in my browser's console, but I know nohing about JS, so a perennial solution would be cool ❤️.

Gouvernathor avatar May 24 '22 13:05 Gouvernathor

hello there, just to bump on the latest comment 😄 I am on windows 10 firefox and it seems right clicking and saving image as always gives me a blank image 😢 I will try the above code as well 😄 or follow your "how it was made" tutorial 👍

EDIT: tested first comment code and it is now saving the image, thank you for this great app 👍

mokalux avatar Jul 08 '23 03:07 mokalux