Sunday, January 22, 2012

HTML5 canvas: Draw Line with lineCap

lineCap attribute defines the type on the end of lines.
  • butt- the end of each line has a flat edge perpendicular to the direction of the line (and that no additional line cap is added).
  • round- a semi-circle with the diameter equal to the width of the line will be added on to the end of the line.
  • square- a rectangle with the length of the line width and the width of half the line width, placed flat against the edge perpendicular to the direction of the line.


Example:
HTML5 canvas: Draw Line with lineCap
<!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){

c.lineWidth = 20;

<!-- default lineCap -->
c.strokeStyle = "#000000";
c.beginPath();
c.moveTo(50, 50);
c.lineTo(150, 50);
c.lineTo(150, 150);
c.lineTo(50, 150);
c.lineTo(50, 50);
c.stroke();
c.closePath();

<!-- lineCap "butt" -->
c.lineCap = "butt";
c.strokeStyle = "#ff0000";
c.beginPath();
c.moveTo(125, 125);
c.lineTo(225, 125);
c.lineTo(225, 225);
c.lineTo(125, 225);
c.lineTo(125, 125);
c.stroke();
c.closePath();

<!-- lineCap "round" -->
c.lineCap = "round";
c.strokeStyle = "#00ff00";
c.beginPath();
c.moveTo(200, 50);
c.lineTo(300, 50);
c.lineTo(300, 150);
c.lineTo(200, 150);
c.lineTo(200, 50);
c.stroke();
c.closePath();

<!-- lineCap "square" -->
c.lineCap = "square";
c.strokeStyle = "#0000ff";
c.beginPath();
c.moveTo(275, 125);
c.lineTo(375, 125);
c.lineTo(375, 225);
c.lineTo(275, 225);
c.lineTo(275, 125);
c.stroke();
c.closePath();

}

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

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

No comments:

Post a Comment