g2 5.0 实现简单文本自动预览

127 阅读1分钟

chrome-capture-2023-7-8.gif

import { Chart } from '@antv/g2';

const words =
  `
  This Is Just To Say\nWilliam Carlos Williams, 1934\n\nI have eaten\nthe plums\nthat were in\nthe icebox\n\nand which\nyou were probably\nsaving\nfor breakfast\n\nForgive me\nthey were delicious\nso sweet\nand so cold\n
  This Is Just To Say\nWilliam Carlos Williams, 1934\n\nI have eaten\nthe plums\nthat were in\nthe icebox\n\nand which\nyou were probably\nsaving\nfor breakfast\n\nForgive me\nthey were delicious\nso sweet\nand so cold\n
  This Is Just To Say\nWilliam Carlos Williams, 1934\n\nI have eaten\nthe plums\nthat were in\nthe icebox\n\nand which\nyou were probably\nsaving\nfor breakfast\n\nForgive me\nthey were delicious\nso sweet\nand so cold\n
  This Is Just To Say\nWilliam Carlos Williams, 1934\n\nI have eaten\nthe plums\nthat were in\nthe icebox\n\nand which\nyou were probably\nsaving\nfor breakfast\n\nForgive me\nthey were delicious\nso sweet\nand so cold\n
  This Is Just To Say\nWilliam Carlos Williams, 1934\n\nI have eaten\nthe plums\nthat were in\nthe icebox\n\nand which\nyou were probably\nsaving\nfor breakfast\n\nForgive me\nthey were delicious\nso sweet\nand so cold\n
  `
    .split('\n')
    .map((d, index) => ({ text: d, key: `${d}${index}` }));

const chart = new Chart({
  container: 'container',
  theme: 'classic',
  autoFit: true,
});

chart
  .text()
  .data({
    value: words.slice(0, 20),
  })
  .encode('x', 0.5)
  .encode('y', (_, idx) => idx)
  .encode('text', 'text')
  .encode('key', 'key')
  .encode('color', (_, idx) => idx)
  .encode('opacity', (_, idx) => idx)
  .scale('y', { type: 'point' })
  .style('textAlign', 'center')
  .style('textBaseline', 'middle')
  .style('fontSize', 16)
  .scale('color', { offset: (t) => 1 - t })
  .axis(false)
  .legend(false);

chart.render();

setInterval(() => {
  words.shift();
  if(words.length > 20)
  chart.changeData(words.slice(0, 20));
}, 1000)

简单说明

一般的数据更新,会覆盖原有的 mask 内容,而不会进行位置的变换。其原因在于 key 属性。 要想在 changeData 变更数据后,原有的形状或者文本,可以在新数据的基础上变化,则需要对 key 属性进行指正。

encode('key',key) , 这样在 changeData 后,相同 key 的形状或文本就和数据对应起来了。在变化的时候,可以不进行重新渲染,而是改变位置或样式。