jameshfisher
jameshfisher

Reputation: 36427

How can I apply a pixel shader to a canvas element?

I have a <canvas> element which is written to by an external library. I wish to apply a "post-production" effect to this canvas: I want to map a function (r,g,b,a) -> (r,g,b,a) over every pixel before it is finally displayed.

I know that the external library writes to a 2D context obtained from the <canvas> element. I also know that the transformation I'm asking for is a "pixel shader" or "fragment shader". I know I will need a webgl context to apply such a shader. I am told by this answer that a canvas cannot have multiple contexts at the same time, so I am not sure this approach is possible.

Another approach I considered is to capture the output of the canvas as a stream, and write it to a new canvas with my transformation applied. However, this feature only exists in bleeding-edge Firefox.

Is it possible to apply a fragment shader to canvas output? If so, how?

Upvotes: 7

Views: 16596

Answers (1)

user128511
user128511

Reputation:

You can copy a 2D canvas to a WebGL texture and render that texture to a WebGL canvas with whatever fragment shader you design.

There's plenty of examples on stack overflow of using a canvas as the source data for a texture

How Do I Use an HTML5 Canvas as a WebGL Texture

how to get texture in webgl?without Canvas.toDataUrl()

Blend two canvases onto one with WebGL

WebGL blit texture to canvas

Upvotes: 9

Related Questions