如何用canvas实现一张图片绕画布中心点自动旋转
时间: 2024-02-05 07:13:17 浏览: 38
你可以遵循以下步骤使用 canvas 实现图片绕画布中心点自动旋转:
1. 获取 canvas 元素和 2D 上下文。
2. 创建一个 Image 对象,设置它的 src 属性为你想要旋转的图片地址。
3. 在 Image 对象的 onload 事件中,设置画布的中心点,然后使用 setInterval() 方法以一定的时间间隔重绘画布。
4. 在重绘画布时,先清除画布,然后将画布中心点设置为旋转中心点,使用 translate() 方法将画布移动到旋转中心点处,使用 rotate() 方法旋转画布,最后使用 drawImage() 方法将图片绘制在画布上。
以下是一个示例代码:
```javascript
// 获取 canvas 元素和 2D 上下文
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// 创建 Image 对象
var img = new Image();
img.src = 'image.jpg';
// 在 Image 对象的 onload 事件中,设置画布的中心点和重绘画布
img.onload = function() {
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var angle = 0;
setInterval(function() {
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 将画布移动到旋转中心点处
ctx.translate(centerX, centerY);
// 旋转画布
ctx.rotate(angle * Math.PI / 180);
// 将图片绘制在画布上
ctx.drawImage(img, -img.width / 2, -img.height / 2);
// 恢复画布状态
ctx.rotate(-angle * Math.PI / 180);
ctx.translate(-centerX, -centerY);
// 更新角度
angle += 1;
}, 10);
};
```
这段代码将每 10 毫秒重绘画布一次,并以每次 1 度的速度旋转画布,从而实现了图片绕画布中心点自动旋转的效果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)