You must be logged in to post your query.
Home › Forums › Chart Support › Converting between pixels and data values
Tagged: chart coordinates
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?
position:relative
// 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 } }
@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
Thank you, Thangaraj! That’s exactly what I was looking for. I missed it in the docs.
You must be logged in to reply to this topic. Login/Register