jQuery-Student1989
jQuery-Student1989

Reputation: 85

Saving Three.js Canvas as image

We have a Carport Designer that uses three.js canvas. I'd like to place a download button to capture the drawing as an image. How would I do that? I've read tons of stuff but nothing I understand.

Thanks in advance!

Edit:

This ended up working for me;

I had to change preserveDrawingBuffer to true.

html

<button id="save">Download Image</button>
<script> document.getElementById('save').onclick=()=>{ saveImage() } function saveImage() { const canvas = document.getElementsByTagName("canvas")[0] const image = canvas.toDataURL("image/png"); const a = document.createElement("a"); a.href = image.replace(/^data:image\/[^;]/, 'data:application/octet-stream'); a.download="image.png" a.click(); } </script>

Upvotes: 2

Views: 1194

Answers (2)

Manojkumar Muthukumar
Manojkumar Muthukumar

Reputation: 321

Create a renderer like below

var renderer: THREE.WebGLRenderer = new THREE.WebGLRenderer({alpha: true,preserveDrawingBuffer: true })

Don't forget to add {alpha: true,preserveDrawingBuffer: true } as params

Create a function for download

public downloadPattern() {
  let canvasImage = renderer.domElement.toDataURL('image/png');
  let a = document.createElement('a');
  a.setAttribute('href', downloadPattern);
  a.setAttribute('download', new Date().getTime() + '.png');
  a.click();
  a.remove();
}

Upvotes: 0

Patrick
Patrick

Reputation: 468

You can create an image object via canvas.toDataURL and then download it:

<!-- html -->
<canvas id="canvas"></canvas>
<button id="btn-download">Download</button>

// javascript
const downloadButton = document.getElementById('btn-download');
const canvas = document.getElementById('canvas');

downloadButton.addEventListener('click', downloadScreenshot);

function downloadScreenshot() {
  const screenshot = canvas.toDataURL("image/png");
  
  let a = document.createElement('a');
  a.href = screenshot;
  a.download = "screenshot.png";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

Upvotes: 1

Related Questions