Search code examples
javascriptmit-scratch

Converting Scratch colours


Scratch appears to be using its own specialised colour format:

Colour slider, Saturation slider and Brightness slider

Is there a way to get the HEX equivalent of these values and is it possible for it to work the other way?


Solution

  • Scratch's colour format CSB uses a format similar to that of HSV (Hue, Saturation, Value) with a few changes.

    • Hue (0-360) becomes Colour (0-100) with its values proportionally scaled down by 3.6x so 36 Hue becomes 10 Colour.
    • Value becomes Brightness with no change

    Converting between CSB and HSV can be done like so:

    // Convert from HSV TO CSB
    const [colour, saturation, brightness] = [Math.round(hue / 360 * 100), saturation, value]
    
    // Convert from CSB to HSV
    const [hue, saturation, value] = [Math.round(colour / 100 * 360), saturation, brightness]
    

    The Math.round function exists incase a hue value is not completely divisible. However, this can pose a problem when using the Touching color block. Since you can only specify Colour values from 0 up to 100, Hues that divide into a decimal number do not work. This can be a problem when using custom sprites from images.

    To fix this, we can quantize the colour so that it is convertible between formats without dealing with decimals. To do so, we can round it to the nearest multiple of 18:

    const compatibleHue = Math.round(hue / 18) * 18