Charts - Save and restore Zoom (the hard way)
import io.data2viz.charts.*
import io.data2viz.charts.dimension.*
import io.data2viz.charts.chart.*
import io.data2viz.charts.chart.mark.*
import io.data2viz.charts.viz.*
import io.data2viz.charts.core.*
import io.data2viz.charts.core.Zoom
import io.data2viz.charts.core.SelectionMode
import io.data2viz.charts.core.Datum
import io.data2viz.charts.layout.*
import io.data2viz.geom.*
import io.data2viz.color.*
import io.data2viz.math.*
import kotlin.random.Random
import kotlinx.browser.document
import org.w3c.dom.*
val numPoint = 200
val randomPoints = (1 .. numPoint).map{ Point(Random.nextDouble(), Random.nextDouble()) }.sortedBy { it.x }
val chartWidth = 700.0
val chartHeight = 500.0
private var displayWidth = chartWidth
private var displayHeight = chartHeight
lateinit var myChart: Chart<Point>
var zoom = Zoom.IDENTITY
fun main() {
// Creating a UI element on top of page, we'll use it to display information
val button1 = document.createElement("button")
button1.innerHTML = "Save zoom"
button1.addEventListener("click", {
saveZoom()
})
document.body!!.appendChild(button1)
// Creating a UI element on top of page, we'll use it to display information
val button2 = document.createElement("button")
button2.innerHTML = "Restore zoom"
button2.addEventListener("click", {
restoreZoom()
})
document.body!!.appendChild(button2)
val vc = newVizContainer().apply {
size = Size(chartWidth, chartHeight)
}
myChart = vc.chart(randomPoints) {
config {
// Disable user-input highlight & selection from the chart
events {
zoomMode = ZoomMode.XY
panMode = PanMode.XY
selectionMode = SelectionMode.None
highlightMode = HighlightMode.None
}
// Display a red cursor
cursor {
show = true
strokeColor = Colors.Web.red
}
}
val xPosition = quantitative( { domain.x } )
val yPosition = quantitative( { domain.y } )
plot(xPosition, yPosition)
}
computeSizes()
}
private fun computeSizes() {
myChart.viewReset()
myChart.pan(100.pct, 100.pct)
displayWidth = myChart.zoom.xZoom.offset
displayHeight = myChart.zoom.yZoom.offset
myChart.viewReset()
}
private fun saveZoom() {
zoom = myChart.zoom
}
private fun restoreZoom() {
myChart.viewReset()
myChart.zoom(0.pct, 0.pct, Percent(zoom.xZoom.ratio), Percent(zoom.yZoom.ratio))
myChart.pan(Percent(zoom.xZoom.offset / displayWidth), Percent(zoom.yZoom.offset / displayHeight))
}
comments