在画布上绘制多个贝塞尔曲线路径
我最近开始在画布上画画。我想画一个圆角矩形,里面有一个圆圈,但圆圈连接到之前的路径。我怎样才能画这个,这样我就不会用一条线连接两个图形?
<html>
<div class="canvas-container">
<canvas id="mistakenBezier">canvas not supported</canvas>
<script type="text/javascript">
var canvas = document.getElementById("mistakenBezier");
if(canvas.getContext){
var ctx = canvas.getContext('2d');
//inputs:
var x = 20, y = 20; //rectangle origin
var w = 160, h = 120; //rectangle size
var r = 10; //rectangle corner radius
//draw rounded rect:
ctx.beginPath();
ctx.moveTo(x,y+h-r);
ctx.lineTo(x,y+r); ctx.bezierCurveTo(x,y,x+r,y,x+r,y);
ctx.lineTo(x+w-r,y); ctx.bezierCurveTo(x+w,y,x+w,y+r,x+w,y+r);
ctx.lineTo(x+w,y+h-r); ctx.bezierCurveTo(x+w,y+h,x+w-r,y+h,x+w-r,y+h);
ctx.lineTo(x+r,y+h); ctx.bezierCurveTo(x,y+h,x,y+h-r,x,y+h-r);
ctx.stroke();
//ctx.closePath();
//draw circle
//ctx.beginPath();
//ctx.moveTo(x,y+h-r);
ctx.arc(x+r+10,y+r+10,r,0,Math.PI*2,true);
//ctx.closePath();
ctx.stroke();
}
</script>
</div>
</html>
I recently started drawing in the canvas. I want to draw a rounded rectangle with a circle inside of it but the circle gets connected to the previous path. How can I draw this so I won't have both figures connected by a line?
<html>
<div class="canvas-container">
<canvas id="mistakenBezier">canvas not supported</canvas>
<script type="text/javascript">
var canvas = document.getElementById("mistakenBezier");
if(canvas.getContext){
var ctx = canvas.getContext('2d');
//inputs:
var x = 20, y = 20; //rectangle origin
var w = 160, h = 120; //rectangle size
var r = 10; //rectangle corner radius
//draw rounded rect:
ctx.beginPath();
ctx.moveTo(x,y+h-r);
ctx.lineTo(x,y+r); ctx.bezierCurveTo(x,y,x+r,y,x+r,y);
ctx.lineTo(x+w-r,y); ctx.bezierCurveTo(x+w,y,x+w,y+r,x+w,y+r);
ctx.lineTo(x+w,y+h-r); ctx.bezierCurveTo(x+w,y+h,x+w-r,y+h,x+w-r,y+h);
ctx.lineTo(x+r,y+h); ctx.bezierCurveTo(x,y+h,x,y+h-r,x,y+h-r);
ctx.stroke();
//ctx.closePath();
//draw circle
//ctx.beginPath();
//ctx.moveTo(x,y+h-r);
ctx.arc(x+r+10,y+r+10,r,0,Math.PI*2,true);
//ctx.closePath();
ctx.stroke();
}
</script>
</div>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您看到的线是因为您需要移动到绘制的圆弧的起点,否则您将从当前位置到您设置圆弧开始绘制的位置绘制一条线。
ctx.moveTo(x+r+10+r,y+r+10); 行需要高于你的弧线呼叫。
一条长路径中的示例
您还可以在矩形的末端进行描边,然后像这样为圆形开始一条新路径。
The line your seeing is because you need to moveto the starting point of the arc your drawing or you will draw a line form the current location to where you set you arc to start drawing.
the line ctx.moveTo(x+r+10+r,y+r+10); needed to be above your arc call.
Example in one long path
You can also stroke at the end of the rectangle and then begin a new path for the circle like so.