# SVG.js动画系列6-舞蹈吧，胖小星!

2020/12/26 20:17

  var star;
const param = {
inner:  50,
outer:  100,
spikes: 5,
edges:  10,
}

function make() {
const color = SVG.Color.random();
star = draw.polygon().star(param).attr({fill:color});
star.move(400, 200);
}

make();

var bx=1,by=1;
function render() {

let x = star.x();
let y = star.y();
x = x + bx*Math.random()*10;
y = y + by*Math.random()*10;
if (x < 100) {x = 100; bx=1;}
else if (x > 650) {x = 650; bx=-1}
if (y < 100) {y = 100; by=1}
else if (y > 400) {y=400; by=-1;}

const color = SVG.Color.random();
const starPoints = getStarPoints();
star.animate({
duration: 300,
delay: 0,
when: 'now',
swing: true,
times: 1,
wait: 0
}).ease('sineInOut').plot(starPoints).move(x, y) //sineInOut elastic
}

var loopCnt = 0;
(function animloop() {
if (0===loopCnt%13) { // one 16ms.
render();
}
loopCnt++;
if (loopCnt > 10000) loopCnt = 0;
window.requestAnimationFrame(animloop);
})();


1. animate之前博客【SVG.js 实现动画系列1】有说过。感兴趣的可以到之前的博客看下各参数的含义。
2. move: 设置图元移动的位置。
3. plot：设置图元点接口，用来改变星星的顶点坐标。starPoints点的变化函数如下：
function getStarPoints(option = {
inner:  50,
outer:  100,
spikes: 5
}, ran=true) {
const {spikes, inner, outer} = option;
var i, a, x, y
, points  = []
, degrees = 360 / spikes

for (i = 0; i < spikes; i++) {
a = i * degrees + 90
x = outer + inner * Math.cos(a * Math.PI / 180) + (ran ? Math.random()*15 : 0)
y = outer + inner * Math.sin(a * Math.PI / 180) + (ran ? Math.random()*10 : 0)

points.push([x, y])

a += degrees / 2
x = outer + outer * Math.cos(a * Math.PI / 180) + (ran ? Math.random()*10 : 0)
y = outer + outer * Math.sin(a * Math.PI / 180) + (ran ? Math.random()*15 : 0)

points.push([x, y])
}

return points;
}


demo源码地址：https://gitee.com/ionep/svg.js-example 如果大家对SVG.js感兴趣请移驾(SVG.js)

0 评论
0 收藏
0