在线咨询
服务热线
服务热线:021-61554458
TOP
网站建设 涿州网站建设> 行业新闻 canvas绘制贝塞尔曲线

canvas绘制贝塞尔曲线

来源:网站建设 | 时间:2015-01-06 | 浏览:

原文:canvas绘制贝塞尔曲线

1、绘制二次方贝塞尔曲线

quadraticCurveTo(cp1x,cp1y,x,y); 其中参数cp1x和cp1y是控制点的坐标,x和y是终点坐标

数学公式表示如下:

二次方贝兹曲线的路径由给定点P0P1P2的函数Bt)追踪:

mathbf{B}(t) = (1 - t)^{2}mathbf{P}_0 + 2t(1 - t)mathbf{P}_1 + t^{2}mathbf{P}_2 mbox{ , } t in [0,1]

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css"> *{padding: 0;margin:0;} body{background: #1b1b1b;} #div1{margin:50px auto; width:300px; height: 300px;} canvas{background: #fff;}
</style>
<script type="text/javascript"> window.onload = function(){     var c = document.getElementById('myCanvas');     var content = c.getContext('2d');          //绘制二次方贝塞尔曲线
    content.strokeStyle ="#FF5D43";     content.beginPath();     content.moveTo(0,200);     content.quadraticCurveTo(75,50,300,200);     content.stroke();     content.globalCompositeOperation = 'source-over';    //目标图像上显示源图像
    
    //绘制上面曲线的控制点和控制线,控制点坐标为两直线的交点(75,50)
    content.strokeStyle = '#f0f';     content.beginPath();     content.moveTo(75,50);     content.lineTo(0,200);     content.moveTo(75,50);     content.lineTo(300,200);     content.stroke();      }; </script>
</head>
<body>
    <div id="div1">
        <canvas id="myCanvas" width="300" height="200"></canvas>
    </div>
</body>
</html>

 

2、三次方贝塞尔曲线

bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y)  其中参数cp1x,cp1y表示第一个控制点的坐标, cp2x,cp2y表示第二个控制点的坐标, x,y是终点的坐标;

数学公式表示如下:

P0P1P2P3四个点在平面或在三维空间中定义了三次方贝兹曲线。曲线起始于P0走向P1,并从P2的方向来到P3。一般不会经过P1P2;这两个点只是在那里提供方向资讯。P0P1之间的间距,决定了曲线在转而趋进P3之前,走向P2方向的“长度有多长”。

mathbf{B}(t)=mathbf{P}_0(1-t)^3+3mathbf{P}_1t(1-t)^2+3mathbf{P}_2t^2(1-t)+mathbf{P}_3t^3 mbox{ , } t in [0,1]

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css"> *{padding: 0;margin:0;} body{background: #1b1b1b;} #div1{margin:50px auto; width:300px; height: 300px;} canvas{background: #fff;}
</style>
<script type="text/javascript"> window.onload = function(){     var c = document.getElementById('myCanvas');     var content = c.getContext('2d');          //三次方贝塞尔曲线
    content.strokeStyle = '#FA7E2A';     content.beginPath();     content.moveTo(25,175);     content.bezierCurveTo(60,80,150,30,170,150);     content.stroke();     content.globalCompositeOperation = 'source-over';          //绘制起点、控制点、终点
    content.strokeStyle = 'red';     content.beginPath();     content.moveTo(25,175);     content.lineTo(60,80);     content.lineTo(150,30);     content.lineTo(170,150);     content.stroke();      }; </script>
</head>
<body>
    <div id="div1">
        <canvas id="myCanvas" width="300" height="200"></canvas>
    </div>
</body>
</html>