vue实现标签云效果的方法详解

2020-06-12 21:22:21易采站长站整理

tags.push(tag);
}
this.tags = tags;//让vue替我们完成视图更新
},

到了这里,我们就算了算坐标,vue完成了视图更新的工作,这时基本上就可以得到一副静态的图像了:
静态标签云
下面就是通过改变每一个tag的x,y的值来使球旋转起来;实现方法是rotateX,rotateY函数:


rotateX(angleX){
var cos = Math.cos(angleX);
var sin = Math.sin(angleX);
for(let tag of this.tags){
var y1 = (tag.y- this.CY) * cos - tag.z * sin + this.CY;
var z1 = tag.z * cos + (tag.y- this.CY) * sin;
tag.y = y1;
tag.z = z1;
}
},
rotateY(angleY){
var cos = Math.cos(angleY);
var sin = Math.sin(angleY);
for(let tag of this.tags){
var x1 = (tag.x - this.CX) * cos - tag.z * sin + this.CX;
var z1 = tag.z * cos + (tag.x - this.CX) * sin;
tag.x = x1;
tag.z = z1;
}
},

这两个函数就是根据标签原来的坐标和球旋转的角度算出新的坐标,最后在mounted钩子下面,写一个animate函数,不断调用这两个函数,实现旋转动画


mounted(){//使球开始旋转
setInterval(() => {
this.rotateX(this.speedX);
this.rotateY(this.speedY);
}, 17)
},

全部


<script>
var app = new Vue({
el: '#app',
data: {
width:700,
height:700,
tagsNum:20,
RADIUS:200,
speedX:Math.PI/360,
speedY:Math.PI/360,
tags: [] },
computed:{
CX(){
return this.width/2;
},
CY(){
return this.height/2;
}
},
created(){//初始化标签位置
let tags=[];
for(let i = 0; i < this.tagsNum; i++){
let tag = {};
let k = -1 + (2 * (i + 1) - 1) / this.tagsNum;
let a = Math.acos(k);
let b = a * Math.sqrt(this.tagsNum * Math.PI);
tag.text = i + 'tag';
tag.x = this.CX + this.RADIUS * Math.sin(a) * Math.cos(b);
tag.y = this.CY + this.RADIUS * Math.sin(a) * Math.sin(b);
tag.z = this.RADIUS * Math.cos(a);
tag.href = 'https://imgss.github.io';
tags.push(tag);
}
this.tags = tags;
},
mounted(){//使球开始旋转
setInterval(() => {
this.rotateX(this.speedX);
this.rotateY(this.speedY);
}, 17)
},
methods: {
rotateX(angleX){