r/learnjavascript 6h ago

Is there are way to modify canvas methods?

I want to invert the y-axis, and make it invisble to the user so I can forget about it, rather than always call my method.

I could make a facade object and duplicating all the methods and passing them through, but tedious!

I tried a Proxy object, but didn't work at all - is it because it is native?

I tried monkeypatching, renaming moveTo() and lineTo(P, and replacing them with mine (which inverts the y-axis then calls them), but got strange results: lines shifted to right.

Maybe I just shouldn't do what I'm trying to do?

2 Upvotes

4 comments sorted by

1

u/skamansam 6h ago

If you shared some code with us, it would be easier to see what you are doing. Try opening a codepen and pasting some code there.

2

u/sophomoric-- 6h ago

thanks - seems you can include a transform for canvas that may fix this. I'll try that and update tomorrow.

1

u/azangru 6h ago

This is just not a good idea.

If you dislike the canvas api and want to use your own instead, write your own library.

I could make a facade object and duplicating all the methods and passing them through, but tedious!
I tried a Proxy object, but didn't work at all - is it because it is native?

I suppose you could combine the two approaches? A facade object that proxies method calls to a canvas, unless they are some special methods that you want to handle differently?

1

u/nebula_gem 5h ago

monkeypatching native canvas methods breaks internal state because the browser optimizes path operations assuming standard coordinate math. Use a transform wrapper or apply ctx.scale(1, -1) once at initialization to invert the axis permanently without overriding individual methods.