0

嗨,我正在查看 LightningChartJs 的 chartXY 文档,似乎找不到向 saveToFile 保存的图像添加时间戳的方法。提前致谢。

4

1 回答 1

1

LightningChart JSsaveToFile不支持添加时间戳。

您可以通过实施自己的储蓄来实现这一目标。

执行此操作的步骤是:

  1. 获取对运行 LightningChart JS 的画布的引用。
const chartCanvas = chart.engine.container.querySelector('canvas')
  1. 将画布内容转换为数据 urlHTMLCanvasElement.toDataURL
const sc = chartCanvas.toDataURL('image/png')
  1. 将该屏幕截图加载到另一个画布
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)
}
  1. 添加时间戳
const timeNow = new Date().toISOString()
ctx.fillStyle = '#fff'
ctx.fillText(timeNow, 0, height)
  1. 将画布上下文保存到文件
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()

请参阅下面的工作示例,单击图表中心的按钮时会存储屏幕截图。

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>

于 2020-07-24T12:29:35.730 回答