jonobr1 / two.js

A renderer agnostic two-dimensional drawing api for the web.
https://two.js.org
MIT License
8.3k stars 455 forks source link

Why is Webgl slower than Canvas? #672

Open tylandercasper opened 1 year ago

tylandercasper commented 1 year ago

I was playing around with your example here: https://codepen.io/jonobr1/pen/QWZZEQ And was surprised that switching to "Two.Types.webgl" performed significantly worse.

I tried updating to the latest (which fixed the graphical issues), but the performance is still pretty slow compared to Canvas. https://codepen.io/tylandercasper/pen/JjZLMeP

Curious as to why this is.

Thanks

jonobr1 commented 1 year ago

Great question. The way the WebGL renderer works is by uploading 2D canvas textures and arranging them in GL space. Since this particular demo is changing the core shape in frame, the renderer needs to re-upload a new canvas texture for each part.

Generally speaking, when you change the style (e.g: fill or stroke) and or the underlying vertices or properties that would affect the shape of a path (like changing a Two.Rectangle's width) these tell the renderer to re-upload a texture. Where you will get gains is when only editing transformations on objects (e.g: Two.Path.position or Two.Path.rotation). The Particle Sandbox example is a good way to measure this and see what operations are fast / slow in different renderers.

Hope this answered your question,

Jamzy01 commented 1 year ago

I assume it is done this way for reasons of consistency, but there is so much potential with WebGL. I tried out the particle sandbox, and I too think canvas 2d is definitely faster, and gives a more crisp image. Do you think there's a chance that the web gl renderer gets re done at some time and made to be better optimized and possibly even given shader support?

jonobr1 commented 1 year ago

Yes, it's certainly on my radar to do. I've been experimenting over the years with a Signed Distance Field way to render all the shapes in Two.js, but haven't come to a final API yet.

In the meantime, you can definitely modify the base shader as explained in these issues: • https://github.com/jonobr1/two.js/issues/186https://github.com/jonobr1/two.js/issues/478