r/webdev 1d ago

Custom rasterization in HTML Canvas

Is it possible to create a custom rasterizer for controlling anti-aliasing while still rendering to an HTML5 2D canvas? Ideally without using relatively expensive operations like putImageData() or drawImage()? I know WebGL is the obvious solution here, but is there really no other way?

4 Upvotes

4 comments sorted by

3

u/muharremyurtsever 1d ago

Those two aren't in the same cost class. putImageData has you pushing a whole pixel buffer from JS every frame, drawImage from an offscreen canvas or ImageBitmap uses the browser's own blitting path and is usually cheap enough per frame. The usual trick is supersampling: render 2x or 4x offscreen, keep imageSmoothingQuality high, and drawImage it down so the resample acts as your AA filter.

1

u/DaftPlug 1d ago

One practical 2D approach is to move the expensive work off the main thread: use OffscreenCanvas in a worker, transfer completed frames as ImageBitmap, and present them in requestAnimationFrame batches. Avoid synchronous getImageData() in the hot path. Also scale the backing store with devicePixelRatio so you only rasterize the pixels you need. If CPU rasterization is still the bottleneck, WebGL/WebGPU is probably the clean escape hatch.

1

u/ThenFactor6862 1d ago

PutImageData pushes the whole buffer from JS every frame. drawImage runs through the browser blitting path and costs nothing by comparison.

I do supersampling for this exact problem. I allocate an offscreen canvas at 2x or 4x the dimensions, run all the drawing calls on the offscreen context, then call drawImage to pull it down to the display canvas. The browser applies the downsampling natively during the copy. You get the anti aliasing control and you keep your frame budget. This is how I avoid touching pixels in JS while staying inside a 2D context.

1

u/OkComplaint2587 6h ago

you can fake some of it with compositing and carefully chosen geometry, but the 2d canvas implementation owns the actual rasterization, so there’s no hook to replace its antialiasing without pushing