 |
Obduction Backer |
Joined: Wed Feb 10, 2010 12:28 am Posts: 1247
|
Today I got to experience once of the joys of programming!
So, I needed to overlay a bunch of transparent layers. Each layer was white but the opacity would be variable. As the layers stacked they became progressively smaller such that the was an gradient of opacity surrounding the final layer in the middle.
Originally I had created an image. As a PNG, it was 17K. But, I figured there must be a way to do it better. So, I wrote some markup to create the image which could be rendered by the client. The biggest challenge was figuring out what the opacity for each layer should be such that the gradient was linear. I toyed with the math and Googled for the answer but I wasn't entirely sure how to describe what I was doing and I couldn't find anything. So, layer by layer, I manually picked opacities until I had the desired result.
[Reveal] Spoiler: If you're curious about the alpha levels I came up with Code: [ 0, 0.0175, 0.02, 0.0225, 0.025, 0.02, 0.02, 0.025, 0.02, 0.02, 0.0275, 0.025, 0.025, 0.0275, 0.025, 0.025, 0.0275, 0.025, 0.025, 0.0325, 0.03, 0.03, 0.0375, 0.03, 0.035, 0.04, 0.035, 0.035, 0.04, 0.04, 0.04, 0.045, 0.0475, 0.045, 0.045, 0.055, 0.05, 0.05, 0.06, 0.06, 0.06, 0.08, 0.07, 0.07, 0.085, 0.08, 0.08, 0.11, 0.1, 0.12, 0.14, 0.14, 0.15, 0.19, 0.21, 0.24, 0.35, 0.42, 0.5, 1 ] This was great, and instead of a 17K image I had 8K of markup. Looking at the opacities I could tell there was a pattern but I I wasn't entirely sure. Starts tiny, ends big. But it's not just divide by 2 from the end otherwise that 0.42 would be 0.25 and that can't be right, can it?
So, I fired up my ever-trusty Excel and plugged in the numbers to get a graph.

YES...I was on to something! That totally looks like something. But what? Perhaps I was right about the divide by two thing?

No...that's not it. What if we do 1 / (<total> - <current>)?

TRIUMPH!!! I plugged in the resulting numbers just to check the end result and it looked fantastic! And with that, I was able to write some code that would generate the markup using that math formula. The end result: 450 bytes. From beginning to end, a savings of like 4000%.
I realize many of you won't really understand why this is cool. And, that's a shame because for me it's an I AM PROGRAMMER HEAR ME ROAR kind of moment. And it's these rare moments that keep me going 
tl;dr for a programmer it feels amazing when you realize your mess of code can be rewritten into a tiny algorithm.
...I feel like I may have started using this thread as a blog. I'm fine with that. 
|
|