我最近开始在画布上画画。我想画一个圆形的矩形,里面有一个圆圈,但圆圈连接到前一个路径。我怎么画这个,所以我不会用线连接这两个数字?
<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>
答案 0 :(得分:1)
你看到的线是因为你需要移动到你的绘图弧的起点,或者你将从当前位置绘制一条线到你设置弧开始绘制的位置。
线ctx.moveTo(x + r + 10 + r,y + r + 10);需要高于你的弧线。
一条长路径中的示例
<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);
//draw circle
ctx.moveTo(x+r+10+r,y+r+10);
ctx.arc(x+r+10,y+r+10,r,0,Math.PI*2,true);
ctx.stroke();
}
</script>
</div>
</html>
您也可以在矩形的末尾描边,然后像这样开始圆的新路径。
<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();
//draw circle
ctx.beginPath()
ctx.arc(x+r+10,y+r+10,r,0,Math.PI*2,true);
ctx.stroke();
}
</script>
</div>
</html>