Created
April 15, 2014 09:34
-
-
Save kejun/10717717 to your computer and use it in GitHub Desktop.
snapsvg + smooth.js (平滑曲线)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
HTML: | |
<script src="//cdnjs.cloudflare.com/ajax/libs/snap.svg/0.2.0/snap.svg-min.js"></script> | |
<script src="http://cloud.github.com/downloads/osuushi/Smooth.js/Smooth-0.1.7.js"></script> | |
<a href="#">spline 1</a> | | |
<a href="#">spline 2</a> | |
*/ | |
var points = [ | |
[5,100], | |
[60,40], | |
[100,120], | |
[140,10], | |
[180,150], | |
[200,80] | |
]; | |
var paper = Snap(300, 300); | |
var p = paper.path({ d: convertToSmoothPathString(interpolatePoints(points)) }); | |
p.attr({ | |
fill: 'none', | |
stroke: '#07a', | |
'stroke-linecap': 'round', | |
strokeWidth: 10 | |
}); | |
var points1 = [ | |
[5,100], | |
[60,20], | |
[100,140], | |
[140,60], | |
[180,100], | |
[200,80] | |
]; | |
var spline1 = function() { | |
p.animate({d: convertToSmoothPathString(interpolatePoints(points))}, 500); | |
}; | |
var spline2 = function() { | |
p.animate({d: convertToSmoothPathString(interpolatePoints(points1))}, 500); | |
}; | |
spline2(); | |
function convertToLineToPathString(points) { | |
var startPoint = points.concat().shift(); | |
var pathString = []; | |
pathString.push('M' + startPoint.join(',')); | |
points.forEach(function(p) { | |
pathString.push('L' + p.join(',')); | |
}); | |
return pathString.join(''); | |
} | |
function convertToSmoothPathString(points) { | |
var startPoint = points.concat().shift(); | |
var pathString = []; | |
var seg; | |
pathString.push('M' + startPoint.join(',')); | |
for (var i = 0, len = points.length; i < len; i+=2) { | |
seg = points.slice(i, i + 2); | |
pathString.push('S' + seg[0].join(',') + ' ' + seg[1].join(',')); | |
} | |
return pathString.join(''); | |
} | |
function interpolatePoints (points) { | |
var pathFunc = Smooth(points.concat(), { | |
method: Smooth.METHOD_CUBIC, | |
clip: Smooth.CLIP_MIRROR, | |
cubicTension: Smooth.CUBIC_TENSION_CATMULL_ROM | |
}); | |
var interpoPoints = []; | |
for (var i = 0, num = points.length; i < num; i += 0.5) { | |
interpoPoints.push(pathFunc(i)); | |
} | |
return interpoPoints; | |
} | |
document.addEventListener('click', function(e) { | |
if (e.target.nodeType > 1 || e.target.tagName && e.target.tagName !== 'A') { | |
return; | |
} | |
e.preventDefault(); | |
if (e.target.innerHTML == 'spline 1') { | |
spline1(); | |
} else if (e.target.innerHTML == 'spline 2') { | |
spline2(); | |
} | |
}, false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
preview: http://cdpn.io/heixL