Skip to content

Instantly share code, notes, and snippets.

@fotinakis
Created April 17, 2019 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fotinakis/66b5ff1d5525db64c81283b8ed13a205 to your computer and use it in GitHub Desktop.
Save fotinakis/66b5ff1d5525db64c81283b8ed13a205 to your computer and use it in GitHub Desktop.
Convert WebGL canvas to static img in place
function canvasToImage(canvas) {
const {top, left, height, width} = canvas.getBoundingClientRect();
const mapImage = document.createElement('img');
mapImage.setAttribute('src', canvas.toDataURL('image/png'));
mapImage.setAttribute('style', `position: absolute; z-index: 2147483638; top: ${top}px; left: ${left}px; width: ${width}px; height: ${height}px;`);
document.body.appendChild(mapImage);
};
// Convert all canvas elements on the page to images.
document.querySelectorAll('canvas').forEach((canvas) => {
canvasToImage(canvas);
});
// This works for 2D canvases or already rendered 3D canvases. For animated 3D canvases
// (with Three.js for example), the resulting image might be transparent. This can be fixed
// by converting the canvas to an image immediately after render. See: https://stackoverflow.com/a/30647502
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment