rt-sim-training-client/src/jmap/painter.js
2019-07-05 00:40:53 +08:00

163 lines
3.6 KiB
JavaScript

import zrender from 'zrender';
import Group from 'zrender/src/container/Group';
import deviceType from './config/deviceType';
import shapefactory from './shape/factory';
import TransformController from './transformController';
const renderer = 'svg';
const devicePixelRatio = 2;
class Painter {
constructor(jamp, opts) {
// 父级实例
this.$jamp = jamp;
// zrender实例
this.$zr = null;
// 图层数据
this.viewLevelMap = {};
// 视图数据
this.viewInstance = {};
// 父级图层
this.parentLevel = null;
// 视图控制器
this.transformController = null;
// 挂载视图
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.parentLevel = new Group({ name: '__parent__' });
this.$zr.add(this.parentLevel);
// 添加子级图层
Object.values(deviceType).forEach(type => {
const level = new Group({ name: `__${type}__` });
this.viewLevelMap[type] = level;
this.parentLevel.add(level);
});
// 视图控制器
this.transformController = new TransformController(this);
}
/**
* 重绘视图
* @param {*} mapDevice
*/
repaint(mapDevice) {
// 清空视图
this.clear();
// 创建视图
Object.values(mapDevice).forEach(device => {
device && this.add(device);
});
}
/**
* 添加视图
* @param {*} device
*/
add(device) {
const type = device._type;
const code = device._code;
const view = shapefactory(type, device, this.$jamp.getStyleDict());
if (view) {
this.transformController.transformView(view);
this.viewInstance[code] = view;
this.viewLevelMap[type].add(view);
}
}
/**
* 删除视图
* @param {*} device
*/
delete(device) {
const code = device._code;
const type = device._type;
const view = this.viewInstance[code];
if (view) {
this.viewLevelMap[type].remove(view);
delete this.viewInstance[code];
}
}
/**
* 更新视图
* @param {*} device
*/
update(device) {
const code = device._code;
const view = this.viewInstance[code];
if (view) {
view.setState(device);
}
}
/**
* 更新zoom
* @param {*} transform
*/
updateZoomTransform(transform) {
Object.assign(this.zoomTransform, transform);
}
/**
* 视图是否存在
* @param {*} code
*/
hasViewInstance(code) {
return this.viewInstance[code];
}
/**
* 刷新画布,将在下一个渲染帧的时候被刷新。
*/
refresh() {
this.$zr && this.$zr.refresh();
}
/**
* 清除所有对象和画布
*/
clear() {
// 清空视图
this.viewInstance = {};
// 清空图层
Object.values(this.viewLevelMap).forEach(level => {
level && level.removeAll();
});
this.refresh();
}
/**
* 销毁 ZRender 实例
*/
dispose() {
this.$zr && zrender.dispose(this.$zr);
this.$zr = null;
this.viewInstance = {};
this.viewLevelMap = {};
}
}
export default Painter;