Created
April 17, 2019 16:38
-
-
Save fotinakis/66b5ff1d5525db64c81283b8ed13a205 to your computer and use it in GitHub Desktop.
Convert WebGL canvas to static img in place
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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