I found a great start for actually drawing the wheel at the canvas color wheel post from Ariya Hidayat. I modified that code and got the wheel on the screen in no time.
I tied together some
buggy bounds checking on the circle for mousemove events and printed out the current RGB using the conversion function above, and I had a cool little demo - weighing in at around 2K.
Smaller… Much Smaller
So I needed to drop about half the weight of the project. I learned that you could use
~~x instead of
Math.floor(x) provided that the number is positive, so that helped. And there are always tricks about passing in assignments to functions to save a semicolon, storing references to global objects, commonly used math functions, and so on. But it was not quite the time for dropping individual bytes, I needed some big changes.
First, DOM and CSS rules take up a lot of bytes.
b.appendChild(d.createElement("input")) is just huge and cannot really be minified beyond what is there. My takeaway was that I needed less DOM elements. I was originally using a container div with a width equal to that of the canvas (400px) and had a little ‘spot’ div that was absolutely positioned based on the current X and current Y value. All of these lines are problems when are you trying to squeeze an ‘application’ into 1k:
By moving this functionality into the canvas drawing method (with fillRect, and later fillText), I dropped a couple hundred more bytes.
Next, the hsvToRgb conversion function got an overhaul (it went from 291 bytes to 205, and 33 of those are for the CSS color rule needed for the RGB background color). Takeaway here is that
case statements have a lot of control characters, and this particular one was nicely shrunk down using 3 arrays.
From there, it was mostly reorganizing and adding hacks to make the code smaller. A tip for anyone trying to do this: I wrap all the code into a executing function, so that minifiers will use one letter names for variables (rather than assuming they are global). Then I run the code through Closure Compiler online frequently when making changes to see how effective changes are. Don’t forget to remove the wrapper from the minified file, though!
I finally got to 1024 bytes! It was a fun project, I will probably to it again when another js1k comes along.