Skip to content
Advertisement

how can i create a segmented colored line using lightning chart js? [closed]

Can anyone draw a segment line using this library?

I tried using addsegmentseries method but it didn’t work.

Advertisement

Answer

Found the answer myself.

A segment can be created using addSegmentSeries() method. Segment coordinates can be passed using add() method.

/**Segment coordinates */
const config = {
    startX: 0,
    startY: 60,
    endX: 20,
    endY: 60
};

/**Line style */
const style = new SolidLine(
      { thickness: 2, fillStyle: new SolidFill({ color: ColorRGBA(0, 125, 0) }) })

let series = chart
    .addSegmentSeries()
    .add(config)
    .setStrokeStyle(style) 
enter code here

One way to draw a segmented line is to compose single sub-segments together.

Here is an example code:

/**Segment division in many sub segments
 * @param segment to split. E.C: { startX: 0, startY: 60, endX: 20, endY: 60 }
 * @param min minimal value to use for segmented line begin
 * @param max maximum value to use for segmented line ending
 * @param offsetPx sub segments lenght */
function getSubSegments(segment, min, max, offsetPx) {
    const range = segment != null ? segment.endX - segment.startX : -1;
    if (range === -1) { return; }
    const dividedSegments = [];
    min = min <= segment.startX ? min : segment.startX - 1000;
    max = max >= segment.endX ? max : segment.endX + 1000;
    let offset = min + offsetPx;
    while (offset <= max) {
        dividedSegments.push({
            startX: dividedSegments.length > 0 ? dividedSegments[dividedSegments.length - 1].endX : min,
            startY: segment.startY,
            endX: offset,
            endY: segment.endY
        });
        offset += offsetPx;
    }
    return dividedSegments;
}

/**Function to draw segments on chart
 * @param chart which will draw segments
 * @param subSegments to draw on chart
 * @param customStrokeStyle to apply to the line
 */
function drawSegmentedLine(chart, subSegments, customStrokeStyle) {
    const lineSeriesObjs = [];
    let index = -1;
    let series = null;
    for (let i = 0; i < subSegments.length - 1; i++) {
        index = i;
        if (i % 2 === 0) {
            let series = chart
                .addSegmentSeries()
                .add(subSegments[i])
                .setStrokeStyle(customStrokeStyle)
        }
    }
}

drawSegmentedLine(
    chart,
    getSubSegments({ startX: 0, startY: 60, endX: 100, endY: 60 }, -1000, 1000, 5),
    new SolidLine({ fillStyle: new SolidFill({ color: ColorRGBA(0, 220, 0) }), thickness: 2 })
)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement