How can I save shadow map as an image?

I want to save the shadow map render target as an image, and I use the follow method,
At the end of WebglShadowMap render function, I add these codes:

var image = document.createElement(‘img’);
var dataURL = _renderer.domElement.toDataURL();
image.src = dataURL;
document.body.appendChild(image);
image
Later, I get the image, but there is nothing on it, I only can see a black picture, what’s wrong with me ?How can I get it truely?

And I even attempting to draw the shadow map texture in a plane geometry, I have pass the textureId to the shader, and the fragment shader like this,
image
But the result is also show a black color. I can confirm that ‘u_texture’ and ‘v_uv’ parameters are correct, but I dont konw why the result.

I need your help,please.

You should study the following example:

https://threejs.org/examples/webgl_shadowmap_viewer.html

It shows how to visualize shadow maps via ShadowMapViewer.

1 Like

Yeah, I find the correct way to draw the shadow map texture on the plane, thanks for your answer.

However,there is still a question that the shadow quality is very low, I set shadow map size 2000 * 2000, is there other way to improve the shadow quality?
now the shadow is look like this:
image

The configuration of the shadow camera has a huge impact on shadow quality. Please have a look at the setup in this example: https://threejs.org/examples/#webaudio_timing

You also might set renderer.shadowMap.type to THREE.PCFSoftShadowMap. PCF stands for Percentage-close filtering.

1 Like

Thanks, I adjust the camera parameter improve a little, but limited.
I find you create shadow map textuer with RGBAFormat and unsigned byte type
image
image

I dont know why you not use gl.depthComponent and gl.Float type for the better precisoin, I think it can help get better shadow quality.

Hey @vaing4723, I don’t know if you had solved this problem. And I met the low quality image too. I figure out it’s a problem about devicePixelRatio. try the code below:

    let expectedWidth = 512
    let expectedHeight = 512
    let devicePixelRatio = window.devicePixelRatio
    canvas.style.width = expectedWidth*devicePixelRatio
    canvas.style.height = expectedHeight*devicePixelRatio
    canvas.width = expectedWidth*devicePixelRatio
    canvas.height = expectedHeight*devicePixelRatio
    var context = canvas.getContext( '2d' );
    renderer.setSize(expectedWidth, expectedHeight)
    renderer.render( scene, camera );
    context.drawImage( renderer.domElement, 0, 0);
    canvas.style.width = expectedWidth
    canvas.style.height = expectedHeight