- Canvas Cookbook
- Bhushan Purushottam Joshi
- 293字
- 2021-07-16 11:03:13
Drawing joins
This topic focuses on the lineJoin
property of the context object.
The lineJoin
property allows you to join two lines with three different effects. They are:
- bevel (default)
- round
- miter
The effect of lineJoin
can be easily observed in the output of our new recipe:

How to do it...
Again a small change in our first recipe makes this recipe.
Replace the drawLine()
function with drawJoinedLines()
and then call this function (three times) from init()
.
The recipe looks like this:
<html>
<head>
<title>Simple Canvas</title>
<script type="text/javascript">
var can;
var ctx;
function init() {
can = document.getElementById("MyCanvasArea");
ctx = can.getContext("2d");
drawJoinedLines(50,150,50,50,20,"blue","round");
drawJoinedLines(50,300,50,200,20,"red","miter");
drawJoinedLines(50,450,50,350,20,"green","bevel");
}
function drawJoinedLines(xstart,ystart,xnext,ynext,width,color,jointype){
ctx.beginPath();
ctx.lineJoin=jointype;
ctx.lineCap="square";
ctx.strokeStyle=color;
ctx.lineWidth=width;
x1=xstart; y1=ystart; x2=xnext; y2=ynext;
ctx.moveTo(x1,y1);
for(i=1;i<=20;i+=1){
ctx.lineTo(x2,y2);
if(i%2==1){ //if 1 line is drawn, move along x axis
x2=x2+50;
}
else{
if(y2>ynext)
y2=ynext;
else
y2=y2+100;
}
}
ctx.stroke();
ctx.closePath();
}
</script>
</head>
<body onload="init()">
<br/><br/>
<center>
<canvas id="MyCanvasArea" height="500" width="600" style="border:3px solid brown;">
</canvas>
</center>
</body>
</html>
How it works...
Here, the main function, which does the job for us, is drawJoinedLines()
. This function is called through the init()
function three times. Obviously the output shows three different ways in which the lines are joined.
Outside the for
loop we move to the (x1,y1)
coordinates to start the drawing. The function lineTo()
mentioned in the loop draws a line between (x1,y1)
and (x2,y2)
. In the first iteration, the vertical line is drawn and the end points for the next line are set. If the line to be drawn is horizontal, we increment the value of x2
by 50
, thus moving along the x axis. If the line to be drawn is vertical, then we increment the value of the y coordinate by 100
moving vertically downwards. The loop executes 20 times, drawing 10
vertical and 10
horizontal lines.
The function drawJoinedLines()
is called three times from init(),
each time specifying the different start point and join type. The effect of the joins can be seen in the output.
- GAE編程指南
- 解構(gòu)產(chǎn)品經(jīng)理:互聯(lián)網(wǎng)產(chǎn)品策劃入門寶典
- SQL Server 2016數(shù)據(jù)庫應(yīng)用與開發(fā)習(xí)題解答與上機指導(dǎo)
- PLC編程與調(diào)試技術(shù)(松下系列)
- Python編程:從入門到實踐
- Service Mesh實戰(zhàn):基于Linkerd和Kubernetes的微服務(wù)實踐
- 小程序,巧應(yīng)用:微信小程序開發(fā)實戰(zhàn)(第2版)
- Oracle數(shù)據(jù)庫編程經(jīng)典300例
- Struts 2.x權(quán)威指南
- 算法圖解
- Akka入門與實踐
- Android技術(shù)內(nèi)幕(系統(tǒng)卷)
- Python數(shù)據(jù)科學(xué)實踐指南
- PHP高性能開發(fā):基礎(chǔ)、框架與項目實戰(zhàn)
- 移動智能系統(tǒng)測試原理與實踐