Home Forums Chart Support Converting between pixels and data values

Converting between pixels and data values

Viewing 3 posts - 1 through 3 (of 3 total)
  • #45085

    Given a chart inside a position:relative container, I’m (successfully) using the following code to convert between pixel coordinates and data values, and back again. Is there a better way than this reaching into the internals?

    
    // pxCoord: {x:pxX, y:pxY}
    // returns: {x:dataX, y:dataY}
    function pxToData(chart, pxCoord) {
        const x = chart.axisX[0], y = chart.axisY[0]
        return {
            x : (pxCoord.x - x.bounds.x1) * (x.dataInfo.max - x.dataInfo.min)/(x.bounds.x2 - x.bounds.x1),
            y : (pxCoord.y - x.bounds.y1) * (y.dataInfo.max - y.dataInfo.min) / (y.bounds.y1 - y.bounds.y2)
        }
    }
    
    // dataCoord: {x:dataX, y:dataY}
    // returns:   {x:pxX, y:pxY}
    function dataToPx(chart, dataCoord) {
        const x = chart.axisX[0], y = chart.axisY[0]
        return {
            x : dataCoord.x * (x.bounds.x2 - x.bounds.x1) / (x.dataInfo.max - x.dataInfo.min) + x.bounds.x1,
            y : dataCoord.y * (y.bounds.y1 - y.bounds.y2) / (y.dataInfo.max - y.dataInfo.min) + y.bounds.y2
        }
    }
    
    • This topic was modified 7 months, 2 weeks ago by Phrogz. Reason: Trying to fix formatting
    #45091

    @phrogz,

    You can use the convertValueToPixel method to get the pixel coordinate for a given value along the axis. Similarly, you can use the convertPixelToValue method to get the value along the axis for a particular pixel coordinate.


    Thangaraj Raman
    Team CanvasJS

    #45094

    Thank you, Thangaraj! That’s exactly what I was looking for. I missed it in the docs.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.