Skip to content

手动绘制一个 Component

花生PeA edited this page Feb 23, 2019 · 2 revisions

既然 drawInfo 代表一个叶子 Component 的所有绘制信息,那我们可不可以手动的填充 drawInfo,然后绘制单个叶子 Component?

当然可以。

我们在入口文件(entry.ts)使用如下代码绘制一组 Event 而不用 Event。

导入和初始化

import 'short-night/styles.css'; // 官方定义的引用 CSS 文件
import {Timeline, ExtensionManager} from 'short-night';
import AxisBody from './Axis/AxisBody';
import EventMark from './Event/EventMark';
import EventBody from './Event/EventBody';
import EventAxis from './Event/EventAxis';

const { canvas, container } = Timeline.mount('#app', 'polar-day');
const ext = new ExtensionManager();

const axisBody = new AxisBody({canvas, container, ext});
const eventMark = new EventMark({canvas, container, ext});
const eventBody = new EventBody({canvas, container, ext});
const eventAxis = new EventAxis({canvas, container, ext});

前边也说过,Timeline.mount是将一个 DOM 节点初始化,其返回一个 canvascontainer DOM节点,这2个 DOM 节点需要在 Short Night Component 构造时传入。在 Component 中,你也可以通过this.canvasthis.container拿到构造时的传入。

ext则稍微复杂了一些,不管我们暂时用不到它,所以直接初始化并传入即可。

手动初始化 drawInfo

接下来就是手动的一项项在 drawInfo 上赋值:

(async function f() {
    axisBody.drawInfo.width = 6;
    axisBody.drawInfo.length = 500;
    axisBody.drawInfo.start = {
        x: 300,
        y: 0,
    };
    await axisBody.apply();
    axisBody.draw();

    eventMark.drawInfo.axisBodyDrawInfo = axisBody.drawInfo;
    eventMark.drawInfo.width = 10;
    eventMark.drawInfo.target = {
        x: axisBody.drawInfo.start.x,
        y: 300
    };
    await eventMark.apply();
    eventMark.draw();

    eventBody.drawInfo.markDrawInfo = eventMark.drawInfo;
    eventBody.drawInfo.date = new Date().toString();
    eventBody.drawInfo.title = 'A evnet';
    eventBody.drawInfo.offset = {
        x: 20,
        y: 0,
    };
    await eventBody.apply();
    eventBody.draw();

    eventAxis.drawInfo.markDrawInfo = eventMark.drawInfo;
    eventAxis.drawInfo.axisBodyDrawInfo = axisBody.drawInfo;
    eventAxis.drawInfo.offsetX = 30;
    eventAxis.drawInfo.length = 100;
    await eventAxis.apply();
    eventAxis.draw();

}());

画出来大概是这样的:

Draw an event manually

上边的代码中,为了使用方便,我们用了一个自执行的异步函数包裹,确保可以使用 await 。

你可能会发现 EventMark 没有盖住上边的横线,这很正常,因为这和draw()的次序有关。