paulroth3d / jupyter-ijavascript-utils

Utility library for working with iJavaScript - a Jupyter Kernel
1 stars 0 forks source link

Include a simple color interpolation #12

Open paulroth3d opened 2 years ago

paulroth3d commented 2 years ago

Colors are frequently used in utils.TableGenerator.styleRow() or .styleCell()

ex:

data = [{ id: 1, val: 2}, { id: 2, val: 5}, { id: 3, val: 2.5}, { id: 4, val: 4}, { id: 5, val: 1}, { id: 6, val: 2.5}, { id: 7, val: 4}];

new utils.TableGenerator(data)
  .formatRows(({ record }) => (record.val > 2) ? 'background-color': 'red' : 'green')
  //-- or a request to interpolate the color from green to red based on the value
  .render()

also in SVG in interpolating colors between one color to another.

Can we include a simple function without dependencies on Format that could provide this?

(if provided as a simple function without dependencies, then it can be used both server side and client - side

paulroth3d commented 2 years ago

Library that does this well color on npm

Likely we would want to pair down the functionality to something similar to the method on svg.js

This will absolutely work in the meantime, and already included in utils.format.svg

var color = new SVG.Color('#ff0066').to('#000')
color.at(0.5).toHex() //-> '#7f0033'

we currently show something like this that works in both embed and render sides in the docs

//-- same instance as the svg.render example
utils.svg.render(({el, SVG, width, height}) => {
    const colorTransition = new SVG.Color('#FF00FF').to('#0FF');

    // draw a rectangle
    const firstRect = el.rect(100, 100)
        .fill('#0FF')
        .center(300, 100);

    // clone the rectangle, color it with the color range, and move it relative
    const secondRect = firstRect.clone()
        .fill(colorTransition.at(0))
        .dx(-200)
        .addTo(el);

    firstRect.clone()
        .fill(colorTransition.at(0.5))
        .dx(-100)
        .addTo(el);
});
paulroth3d commented 2 years ago

Someone could also always use d3 and their scale chromatics https://github.com/d3/d3-scale-chromatic

colorScale = d3.scaleSequential()
    .domain([0,99])
    .interpolator(d3.interpolate("purple", "orange"));

colorScale(50) // color halfway between purple and orange

more detail can be found here: http://using-d3js.com/04_05_sequential_scales.html

paulroth3d commented 2 years ago

perhaps something like:

// utils.format.interpolateColor( string:hexColorFrom, string:hexColorTo, [domain:min = 0, domain:max = 1])
const colorRange = utils.format.interpolateColor('#ff0066', '#000', [0, 10]);
colorRange(0.5) // '#7f0033'
paulroth3d commented 1 year ago

interpolating colors is something that is needed quite frequently d3 does this much better, but it can be nicer when you don't have to retool to also include d3 just so you can run colors