標籤:style blog class code c java
我們知道二次方貝茲路徑,那些曲線都是二維的,意思就是說,它們都只能向一個方向彎曲。如果需要這樣,能夠向兩個方向彎曲的曲線,那麼你需要的就是三次貝茲路徑。
該圖所示應用程式使用bezierCurveTo()方法建立了一條代表三次方貝茲曲線的路徑。該應用程式的代碼列在了下面的程式清單中。
這段代碼除了繪製曲線本身,還填充了表示曲線控制點與錨點的小圓圈。
html代碼:
1 <html> 2 <head> 3 <title>Bezier Curves</title> 4 5 <style> 6 body { 7 background: #eeeeee; 8 } 9 10 #canvas {11 background: #ffffff;12 cursor: pointer;13 margin-left: 10px;14 margin-top: 10px;15 -webkit-box-shadow: 4px 4px 8px rgba(0,0,0,0.5);16 -moz-box-shadow: 4px 4px 8px rgba(0,0,0,0.5);17 box-shadow: 4px 4px 8px rgba(0,0,0,0.5);18 }19 </style>20 </head>21 22 <body>23 <canvas id=‘canvas‘ width=‘600‘ height=‘400‘>24 Canvas not supported25 </canvas>26 27 <script src = ‘example.js‘></script>28 </body>29 </html>
example.js代碼:
1 var canvas = document.getElementById(‘canvas‘), 2 context = canvas.getContext(‘2d‘), 3 endPoints = [ 4 { x: 130, y: 70 }, 5 { x: 430, y: 270 }, 6 ], 7 controlPoints = [ 8 { x: 130, y: 250 }, 9 { x: 450, y: 70 },10 ];11 12 function drawGrid(color, stepx, stepy) {13 context.save()14 15 context.strokeStyle = color;16 context.fillStyle = ‘#ffffff‘;17 context.lineWidth = 0.5;18 context.fillRect(0, 0, context.canvas.width, context.canvas.height);19 20 for (var i = stepx + 0.5; i < context.canvas.width; i += stepx) {21 context.beginPath();22 context.moveTo(i, 0);23 context.lineTo(i, context.canvas.height);24 context.stroke();25 }26 27 for (var i = stepy + 0.5; i < context.canvas.height; i += stepy) {28 context.beginPath();29 context.moveTo(0, i);30 context.lineTo(context.canvas.width, i);31 context.stroke();32 }33 34 context.restore();35 }36 37 function drawBezierCurve() {38 context.strokeStyle = ‘blue‘;39 context.fillStyle = ‘yellow‘;40 41 context.beginPath();42 context.moveTo(endPoints[0].x, endPoints[0].y);43 context.bezierCurveTo(controlPoints[0].x, controlPoints[0].y,44 controlPoints[1].x, controlPoints[1].y,45 endPoints[1].x, endPoints[1].y);46 context.stroke();47 }48 49 function drawEndPoints() {50 context.strokeStyle = ‘blue‘;51 context.fillStyle = ‘red‘;52 53 endPoints.forEach( function (point) {54 context.beginPath();55 context.arc(point.x, point.y, 5, 0, Math.PI*2, false);56 context.stroke();57 context.fill();58 });59 }60 61 function drawControlPoints() {62 context.strokeStyle = ‘yellow‘;63 context.fillStyle = ‘blue‘;64 65 controlPoints.forEach( function (point) {66 context.beginPath();67 context.arc(point.x, point.y, 5, 0, Math.PI*2, false);68 context.stroke();69 context.fill();70 });71 }72 73 drawGrid(‘lightgray‘, 10, 10);74 75 drawControlPoints();76 drawEndPoints();77 drawBezierCurve();
總結了bezierCurveTo()方法的用法。
bezierCurveTo(double cpx,double cpy,double cp2x,double cp2y,double x,double y):建立一條代表三次方貝茲曲線的路徑。你需要向該方法傳入三個點的座標,前兩點是該曲線的控制點,最後一個店是錨點。