canvas 圆角图片
时间: 2023-09-14 13:11:30 浏览: 45
可以通过使用 `canvas` 的 `drawImage()` 方法和 `arc()` 方法来绘制一个带有圆角的图片。首先,需要将图片加载到 `canvas` 上,然后使用 `arc()` 方法绘制圆角。具体步骤如下:
1. 创建一个 `canvas` 元素和一个 `image` 元素,并将图片加载到 `image` 元素中。
```html
<canvas id="myCanvas"></canvas>
<img id="myImage" src="path/to/image">
```
2. 在 JavaScript 中获取 `canvas` 和 `image` 元素,并将图片绘制到 `canvas` 上。
```javascript
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const img = document.getElementById("myImage");
ctx.drawImage(img, 0, 0);
```
3. 使用 `arc()` 方法绘制圆角。该方法需要指定圆心坐标、半径、起始角度和结束角度。
```javascript
const radius = 20;
const x = 0;
const y = 0;
const width = canvas.width;
const height = canvas.height;
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.clip();
```
4. 最后,将绘制好的圆角图片保存到变量中或者直接在 `canvas` 上显示。
```javascript
const roundedImg = canvas.toDataURL();
```
完整代码示例:
```html
<canvas id="myCanvas"></canvas>
<img id="myImage" src="path/to/image">
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const img = document.getElementById("myImage");
ctx.drawImage(img, 0, 0);
const radius = 20;
const x = 0;
const y = 0;
const width = canvas.width;
const height = canvas.height;
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.clip();
const roundedImg = canvas.toDataURL();
</script>
```