码迷,mamicode.com
首页 > Web开发 > 详细

使用raphael.js根据点坐标绘制平滑曲线

时间:2015-09-30 17:48:48      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:

使用raphael.js根据点坐标绘制平滑曲线

难点:需要理解svg如何使用贝塞尔曲线;如何获得贝塞尔曲线的锚点坐标。

效果图:

技术分享

 

代码:

<html>
<head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta charset="utf-8">
        <title>Carl Test</title>
        <script src="./js/raphael.js"></script>        
</head>
<body>
<div id="carl"></div>

<script>
window.onload = function () {
    
    //获取锚点
    function getAnchors(p1x, p1y, p2x, p2y, p3x, p3y) {
        var l1 = (p2x - p1x) / 2,
            l2 = (p3x - p2x) / 2,
            a = Math.atan((p2x - p1x) / Math.abs(p2y - p1y)),
            b = Math.atan((p3x - p2x) / Math.abs(p2y - p3y));
        a = p1y < p2y ? Math.PI - a : a;
        b = p3y < p2y ? Math.PI - b : b;
        var alpha = Math.PI / 2 - ((a + b) % (Math.PI * 2)) / 2,
            dx1 = l1 * Math.sin(alpha + a),
            dy1 = l1 * Math.cos(alpha + a),
            dx2 = l2 * Math.sin(alpha + b),
            dy2 = l2 * Math.cos(alpha + b);
        return {
            x1: p2x - dx1,
            y1: p2y + dy1,
            x2: p2x + dx2,
            y2: p2y + dy2
        };
    }
    
   
    
    (function(){
        var data = [{x:35,y:180},{x:125,y:59},{x:250,y:180},{x:450,y:70},{x:530,y:170}];
        var paper = Raphael("carl", 800, 300); 
        
        var p;
        for(var i=0, ii = data.length; i<data.length;i++){
            var point = data[i];
            var x = point.x;
            var y = point.y;
            if(!i){
                 p = ["M", x, y, "C", x, y];
            }
            if (i && i < ii - 1) {
               var point1 = data[i-1];
               var point2 = data[i+1];
                var a = getAnchors(point1.x, point1.y, x, y, point2.x, point2.y);//获取锚点
                p = p.concat([a.x1, a.y1, x, y, a.x2, a.y2]);
                
                paper.circle(a.x1, a.y1).attr({fill: "red",stroke:"#fff",r:3});//锚点
                paper.circle(a.x2, a.y2).attr({fill: "red",stroke:"#fff",r:3});//锚点
                paper.path(M+a.x1+,+a.y1+ L+x+,+y).attr({stroke:"red"});//锚点到点的连线
                paper.path(M+a.x2+,+a.y2+ L+x+,+y).attr({stroke:"red"});//锚点到点的连线
            }
            
            paper.circle(x,y).attr({fill: "#34C400",stroke:"#fff",r:3});
            
        }
        p = p.concat([x,y,x,y]);
        paper.path().attr({path:p}).attr({stroke:"#34C400"});
        
    })();
                
};
</script>
</body>
</html>

 

 

查看:

技术分享

 

技术分享

使用raphael.js根据点坐标绘制平滑曲线

标签:

原文地址:http://www.cnblogs.com/jinhuazhe2013/p/4849563.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!