js canvas绘制圆角矩形
时间: 2023-05-11 19:01:44 浏览: 182
可以使用 arc() 方法来绘制圆角矩形,具体实现可以参考以下代码:
function drawRoundRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.arcTo(x + width, y, x + width, y + radius, radius);
ctx.lineTo(x + width, y + height - radius);
ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius);
ctx.lineTo(x + radius, y + height);
ctx.arcTo(x, y + height, x, y + height - radius, radius);
ctx.lineTo(x, y + radius);
ctx.arcTo(x, y, x + radius, y, radius);
ctx.closePath();
ctx.fill();
}
其中,ctx 表示 canvas 的上下文对象,x、y 分别表示圆角矩形的左上角坐标,width、height 表示矩形的宽高,radius 表示圆角的半径。
相关问题
canvas绘制圆角矩形
可以使用canvas的arc()和lineTo()方法来绘制圆角矩形。
首先,绘制左上角的圆弧:
```
ctx.beginPath();
ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 1.5);
```
其中,x和y是矩形左上角的坐标,radius是圆角的半径。
然后,绘制上边的线段:
```
ctx.lineTo(x + width - radius, y);
```
其中,width是矩形的宽度。
接着,绘制右上角的圆弧:
```
ctx.arc(x + width - radius, y + radius, radius, Math.PI * 1.5, Math.PI * 2);
```
然后,绘制右边的线段:
```
ctx.lineTo(x + width, y + height - radius);
```
其中,height是矩形的高度。
接着,绘制右下角的圆弧:
```
ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI * 0.5);
```
然后,绘制下边的线段:
```
ctx.lineTo(x + radius, y + height);
```
接着,绘制左下角的圆弧:
```
ctx.arc(x + radius, y + height - radius, radius, Math.PI * 0.5, Math.PI);
```
最后,绘制左边的线段并填充颜色:
```
ctx.lineTo(x, y + radius);
ctx.fillStyle = color;
ctx.fill();
```
其中,color是要填充的颜色。
完整的代码如下:
```
function drawRoundRect(ctx, x, y, width, height, radius, color) {
ctx.beginPath();
ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 1.5);
ctx.lineTo(x + width - radius, y);
ctx.arc(x + width - radius, y + radius, radius, Math.PI * 1.5, Math.PI * 2);
ctx.lineTo(x + width, y + height - radius);
ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI * 0.5);
ctx.lineTo(x + radius, y + height);
ctx.arc(x + radius, y + height - radius, radius, Math.PI * 0.5, Math.PI);
ctx.lineTo(x, y + radius);
ctx.fillStyle = color;
ctx.fill();
}
```
QML canvas绘制圆角矩形
在QML(Qt Meta Language)中,Canvas是一个用于绘制图形的基本元素。如果你想在Canvas上绘制一个圆角矩形,你可以使用`PathElement`和`Rect`组件配合使用。以下是一个简单的示例:
```qml
import QtQuick 2.0
import QtQuick.Controls 2.0
Rectangle {
id: myRect
anchors.fill: parent
color: "white"
// 创建一个PathElement实例,并设置开始、结束点和圆角半径
PathElement { x: 5; y: 5; type: PathElement.MoveTo }
PathElement { x: parent.width - 10; y: 5; type: PathElement.LineTo }
PathElement { x: parent.width - 10; y: parent.height - 10; type: PathElement.LineTo }
PathElement { x: 5; y: parent.height - 10; type: PathElement.LineTo }
PathElement { x: 5; y: 5; type: PathElement.CloseSubpath }
// 使用PathGenerator渲染这个圆角矩形
Canvas {
clipPath: RectangleClip { source: myRect }
path: PathGenerator { elements: [myRect.path] }
}
}
```
在这个例子中,我们首先创建了一个矩形的路径,通过移动到四个角落并闭合路径,形成了圆角矩形。然后,我们将这个路径应用到了Canvas的clipPath属性上,这样Canvas的内容就会被限制在这个圆角矩形内。
阅读全文
相关推荐















