Добавить метку времени к изображению, сгенерированному SavetoFile

Привет, я просматривал документы chartXY для LightningChartJs и не мог найти способ добавить метку времени к изображению, сохраненному с помощью saveToFile. Заранее спасибо.

1 ответ

Решение

LightningChart JS saveToFile не поддерживает добавление метки времени.

Вы можете добиться этого, реализовав собственное сохранение.

Для этого нужно:

  1. Получите ссылку на холст, на котором работает LightningChart JS.
const chartCanvas = chart.engine.container.querySelector('canvas')
  1. Преобразуйте содержимое холста в URL-адрес данных с помощью HTMLCanvasElement.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>

Другие вопросы по тегам