rt-sim-training-client/src/jmap/painter.js
2019-07-04 09:20:51 +08:00

127 lines
2.9 KiB
JavaScript

import zrender from 'zrender';
import Group from 'zrender/src/container/Group';
import deviceType from './config/deviceType';
import shapefactory from './shape/factory';
const renderer = 'svg';
const devicePixelRatio = 2;
class Painter {
constructor(jamp, opts) {
// 父级实例
this.$jamp = jamp;
// zrender实例
this.$zr = null;
// 图层数据
this.viewLevelMap = {};
// 视图数据
this.viewInstance = {};
// 父级图层
this.parentLevel = new Group({ name: '__parent__' });
// 挂载视图
this.mount(opts.dom, Object.assign({ renderer, devicePixelRatio, width: opts.dom.width, height: opts.dom.clientHeight }, opts.config));
}
/**
* 挂载视图
* @param {*} dom
* @param {*} config
*/
mount(dom, config) {
// 挂载页面视图
this.$zr = zrender.init(dom, config);
// 添加父级图层
this.$zr.add(this.parentLevel);
// 添加子级图层
Object.values(deviceType).forEach(type => {
let level = new Group({ name: `__${type}__` })
this.viewLevelMap[type] = level;
this.parentLevel.add(level);
})
}
/**
* 初次渲染视图
* @param {*} mapDevice
*/
render(mapDevice, styleDict) {
// 清空视图
this.viewInstance = {};
// 清空图层
Object.values(this.viewLevelMap).forEach(level => {
level && level.removeAll();
})
// 创建视图
Object.values(mapDevice).forEach(device => {
device && this.add(device, styleDict);
})
}
/**
* 添加视图
* @param {*} device
*/
add(device, styleDict) {
let type = device._type;
let code = device._code;
let view = shapefactory(type, device, styleDict);
if (view) {
this.viewInstance[code] = view;
this.viewLevelMap[type].add(view);
}
}
/**
* 删除视图
* @param {*} device
*/
delete(device) {
let code = device._code;
let type = device._type;
let view = this.viewInstance[code];
if (view) {
this.viewLevelMap[type].remove(view);
delete this.viewInstance[code];
}
}
/**
* 更新视图
* @param {*} device
*/
update(device) {
let code = device._code;
let view = this.viewInstance[code];
if (view) {
view.setStatus(device);
}
}
/**
* 清除所有对象和画布
*/
clear() {
this.$zr && this.$zr.clear();
}
/**
* 销毁 ZRender 实例
*/
dispose() {
this.$zr && zrender.dispose(this.$zr);
this.$zr = null;
this.viewInstance = {};
this.viewLevelMap = {};
}
}
export default Painter;