如何在html canvas元素中绘制两个圆之间的线

时间:2017-07-21 10:32:08

标签: html5 canvas

我是HTML画布的初学者,我正在尝试创建一个设计,我可以在两个圆圈之间创建一条水平线这里是我想要的画布,直到现在我无法弄清楚我如何加入这两个圆圈行

//Script to draw the canvas 
var canvas1 = document.getElementById("c1");
var canvasobj = canvas1.getContext("2d");
canvasobj.lineWidth = 10;
canvasobj.beginPath();
canvasobj.strokeStyle = "red";
canvasobj.fillStyle = "orange";
canvasobj.arc(100, 100, 60, 0, 2 * Math.PI);
canvasobj.moveTo(100, 0);
canvasobj.lineTo(100, 240);
canvasobj.stroke();
canvasobj.fill();
canvasobj.beginPath();
canvasobj.moveTo(5000, 0);
canvasobj.lineTo(0, 0);
canvasobj.stroke();
canvasobj.beginPath();
canvasobj.arc(500, 100, 60, 0, 2 * Math.PI);
canvasobj.moveTo(500, 0);
canvasobj.lineTo(500, 240);
canvasobj.stroke();
canvasobj.fill();
<canvas id="c1" class="drawncanvas" width="1500" height="500" style="border:1px solid red;"></canvas>

JS小提琴链接:https://jsfiddle.net/daz_001/kvw4n9pu/

1 个答案:

答案 0 :(得分:2)

如果我们想要逐行连接,我们需要两个用于线条绘制的输入,一个是开始点和结束点。所以我们可以从我们用来绘制圆的圆点的中心得到两点。还有一点需要注意的是,这两个外部是圆形的,而不是从中心连接,所以我们需要用线点加上或减去圆的半径。

&#13;
&#13;
//Script to draw the canvas 
                    var canvas1 = document.getElementById("c1");
                    var canvasobj = canvas1.getContext("2d");
                    canvasobj.lineWidth = 10;
                    canvasobj.beginPath();
                    canvasobj.strokeStyle ="red";
                    canvasobj.fillStyle="orange";
                    canvasobj.arc(100,100,60,0,2*Math.PI);
                    canvasobj.moveTo(100,0);
                    canvasobj.lineTo(100,240);
                    canvasobj.stroke();
                    canvasobj.fill(); 
                    canvasobj.beginPath();
                    canvasobj.moveTo(5000,0);
                    canvasobj.lineTo(0,0);
                    canvasobj.stroke();
                    canvasobj.beginPath();
                    canvasobj.arc(500,100,60,0,2*Math.PI);
                    canvasobj.moveTo(500,0);
                    canvasobj.lineTo(500,240); canvasobj.stroke();
                    canvasobj.fill();
                    canvasobj.beginPath();
                    canvasobj.moveTo(160,100); // this is the begining point of the line (x,y)
                    canvasobj.lineTo(440,100);// this is the ending point of the line (x,y)
                    
                    //if you want to connect two circle by outer area. In the begining point we need to add the circle radius with x value also need to reduce the x value from ending point
                    canvasobj.stroke();
&#13;
<canvas id="c1" class="drawncanvas"  width="1500" height="500" style="border:1px solid red;"></canvas> 
&#13;
&#13;
&#13;

Updated fiddle link