BIT-101
Bill Gates touched my MacBook Pro
Just a quick one to verbalize a choice I often make but never thought much about.
Say you want to draw a 100-pixel line, starting at point A, and extending at an angle of 30 degrees (PI/6 radians).
A. You can do it with math. Using trig to find the end point of the line. Here’s some pseudocode, but should work similarly in many systems.
context.moveto(pointA.x, pointA.y)
context.lineto(pointA.x + cos(pi / 6) * 100, pointA.y + sin(pi / 6) * 100)
context.stroke()
B. You can transform the canvas and draw a 0 degree line to 100, 0.
context.save()
context.translate(pointA.x, pointA.y)
context.rotate(pi / 6)
context.moveto(0, 0)
context.lineto(100, 0)
context.stroke()
context.restore()
Stategy B has more steps. You have to save the context’s transform and restore it later, translate to the starting point to get things to rotate from that, do the rotation, then draw the line.
Strategy A, while fewer lines of code, requires more complex math.
Doing a bunch of fairly unscientific profiling tests in cairographics with Go bindings, the trig method generally wins out slightly, but not always. It’s pretty close.
So I can’t make a play on performance. You’d have to test your own code in your own platform.
I will say though, that if you’re drawing multiple shapes all rotated at the same angle from the same point, of course you should be transforming the context and then drawing them all.
On the other hand, if the location of that final point is important for some reason - maybe you want to color the line differently if it intersects some other shape - using trig and knowing the untransformed location of that second point would probably be the way to go.
But for the simple one-off cases, sometimes the trig method feels right, and sometimes the transform feels like the more obvious choice.
Comments? Best way to shout at me is on Mastodon ![]()