第一次加载完svg图后可以获取到SVG 元素的 viewBox 属性,而过段时间后再获取viewBox就变为null了,是什么原因影响的呢
相同条件下:
这样可以获取到height,const viewBox = container.querySelector('svg').getAttribute('height');
这样却获取不到viewBoxconst viewBox = container.querySelector('svg').getAttribute('viewBox');
svg图是有viewBox属性的,第一次加载完svg可以拿到。我这边写了定时器,每隔一分钟再去获取viewBox时就变为null了
以下是补充问题内容:
首次加载svg
initSvg(){
//加载svg图并定义点击事件
var _this = this;
Snap.load(this.details.url + '?v=12345', function (g) {
const container = _this.$refs.svgContainer;
container.appendChild(g.node);
_this.snapAdddwd();
// 初始化svg-pan-zoom实例并绑定到SVG元素上
const options = {
zoomEnabled: true,
controlIconsEnabled: false,
fit: true,
center: true
};
});
},
在加载完的svg图上添加定位方法
snapAdddwd() {
var _this = this;
//已定位组态图监测点
const params = {
zttId: _this.queryParams.jxt,
stationSn: _this.queryParams.stationSn
}
getDqjxt(params).then(response => {
_this.svg1 = Snap("#guidao_svg svg");
const container = _this.$refs.svgContainer;
//这时可以获取到viewBox
const viewBox = container.querySelector('svg').getAttribute('viewBox');
var ratio = 1
if (viewBox) {
let boxArr = viewBox.split(" ");
if(boxArr.length==1)
{
boxArr = viewBox.split(",");
}
const rect = container.querySelector('svg').getBoundingClientRect();
//计算画布尺寸和画布上显示区域的比例
ratio = Math.min(rect.width / boxArr[2], rect.height / boxArr[3]);
}
_this.ratio = ratio;
//描点逻辑代码省略。。。
const options = {
zoomEnabled: true,
controlIconsEnabled: false,
fit: true,
center: true
};
const panZoomInstance = svgPanZoom(container.querySelector('svg'), options);
});
},
定时器方法
mounted() {
this.interval = setInterval(() => {
this.updateAdddwd();//只更新数据
}, 60000);
},
更新数据updateAdddwd()方法
updateAdddwd() {
var _this = this;
//已定位组态图监测点
const params = {
zttId: _this.queryParams.jxt,
stationSn: _this.queryParams.stationSn
}
getDqjxt(params).then(response => {
_this.svg1 = Snap("#guidao_svg svg");
if(_this.svg1 != null){
const container = _this.$refs.svgContainer;
const viewBox = container.querySelector('svg').getAttribute('viewBox');
//此时获取到的viewBox 就为null了
console.log("JSON.stringify(viewBox)::"+JSON.stringify(viewBox))
var g =_this.svg1.select('#myGroupId')
const options = {
zoomEnabled: true,
controlIconsEnabled: false,
fit: true,
center: true
};
const panZoomInstance = svgPanZoom(container.querySelector('svg'), options);
}
});
},
所以产生疑问为什么只在首次加载完svg后执行的snapAdddwd()方法中可以获取到viewBox,而在间隔60秒后触发的定时器执行的updateAdddwd()方法中获取到的viewBox就为null了?