Wednesday, January 25, 2012

HTML5: draw cubic Bézier curve using bezierCurveTo()

The bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) method must ensure there is a subpath for (cp1x, cp1y), and then must connect the last point in the subpath to the given point (x, y) using a cubic Bézier curve with control points (cp1x, cp1y) and (cp2x, cp2y). Then, it must add the point (x, y) to the subpath.

Example:
HTML5: draw cubic Bézier curve using bezierCurveTo()

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Mobile-Web-App: HTML5 Canvas</title>
<script type="text/javascript">
function loadcanvas(){
var canvas;
var context;

//get element by ID of "mycanvas"
canvas = document.getElementById("mycanvas");

//create a "2d" context object
context = canvas.getContext("2d");

drawPath(context);
}

function drawPath(c){

drawBezierCurveTo(c, 50, 50, 100, 0, 250, 150, 300, 50);

for (i = 0; i <= 350; i = i + 20)
{
drawBezierCurveTo(c, 50, 250, 100, 200, i, i, 300, 250);
}
}

function drawBezierCurveTo(c, moveToX, moveToY, cp1x, cp1y, cp2x, cp2y, x, y){

c.lineWidth = 3;

c.strokeStyle = "#000000";
c.beginPath();
c.moveTo(moveToX, moveToY);
c.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
c.stroke();


}

</script>
</head>
<body onload="loadcanvas();">
<h1>Mobile-Web-App: HTML5 canvas</h1>

<canvas id="mycanvas" style="border: 5px solid;" width="400" height="350">
Sorry! Your browser doesn't support Canvas.
</canvas>
</body>
</html>

No comments:

Post a Comment