问题
Hi I was checking out the docs of chartXY of LightningChartJs and couldn't seem to find a way to add a timestamp to the image saved by saveToFile. Thanks in advance.
回答1:
LightningChart JS saveToFile doesn't support adding a timestamp.
You can achieve this by implementing your own saving.
The steps to do this is:
- Get reference to the canvas LightningChart JS is running in.
const chartCanvas = chart.engine.container.querySelector('canvas')
- Convert the canvas content to a data url with HTMLCanvasElement.toDataURL
const sc = chartCanvas.toDataURL('image/png')
- Load that screenshot to another canvas
const secondaryCanvas = document.createElement('canvas')
const ctx = secondaryCanvas.getContext('2d')
const img = new Image()
img.src = sc
img.onload = () => {
// load the screenshot to another canvas
ctx.canvas.width = width
ctx.canvas.height = height
ctx.drawImage(img, 0, 0)
}
- Add the timestamp
const timeNow = new Date().toISOString()
ctx.fillStyle = '#fff'
ctx.fillText(timeNow, 0, height)
- Save the canvas context to file
const timestamped = ctx.canvas.toDataURL('image/png')
const fileName = 'chart.png'
const a = window.document.createElement('a')
window.document.body.appendChild(a)
const url = timestamped
a.href = url
a.download = fileName
a.click()
See a working example below, where a screenshot is stored when the button at the center of chart is clicked.
const {
lightningChart,
UIElementBuilders
} = lcjs
const chart = lightningChart().ChartXY()
const secondaryCanvas = document.createElement('canvas')
const ctx = secondaryCanvas.getContext('2d')
const chartCanvas = chart.engine.container.querySelector('canvas')
document.body.appendChild(secondaryCanvas)
const scButton = chart.addUIElement(UIElementBuilders.ButtonBox)
scButton.setText('Take Screenshot with timestamp')
scButton.setPosition({ x: 50, y: 50 })
scButton.onMouseClick(() => {
const width = chartCanvas.clientWidth
const height = chartCanvas.clientHeight
// screenshot the canvas
const sc = chartCanvas.toDataURL('image/png')
const img = new Image()
img.src = sc
img.onload = () => {
// load the screenshot to another canvas
ctx.canvas.width = width
ctx.canvas.height = height
ctx.drawImage(img, 0, 0)
// add time stamp
const timeNow = new Date().toISOString()
ctx.fillStyle = '#fff'
ctx.fillText(timeNow, 0, height)
// save to file
const timestamped = ctx.canvas.toDataURL('image/png')
const fileName = 'chart.png'
const a = window.document.createElement('a')
window.document.body.appendChild(a)
const url = timestamped
a.href = url
a.download = fileName
a.click()
}
})
<script src="https://unpkg.com/@arction/lcjs@1.3.1/dist/lcjs.iife.js"></script>
来源:https://stackoverflow.com/questions/63035619/add-timestamp-to-image-generated-by-savetofile