canvas 图片旋转
时间: 2023-08-03 12:46:20 浏览: 43
可以使用 Canvas API 中的 `rotate()` 方法来旋转图片。下面是一个简单的例子:
```html
<canvas id="myCanvas"></canvas>
```
```javascript
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const img = new Image();
img.src = "path/to/image.png";
img.onload = () => {
const x = canvas.width / 2;
const y = canvas.height / 2;
const angle = 45 * Math.PI / 180; // 旋转角度,这里是 45 度
ctx.translate(x, y);
ctx.rotate(angle);
ctx.drawImage(img, -img.width / 2, -img.height / 2);
};
```
这段代码将在画布中心绘制一张图片,并将其旋转 45 度。可以通过调整 `angle` 变量来改变旋转角度。注意,旋转是以画布中心为基准进行的,因此需要先使用 `translate()` 方法将坐标系移动到画布中心。另外,`drawImage()` 方法的第一个参数为要绘制的图片对象,第二个和第三个参数为图片的左上角坐标,这里使用了负数来使图片居中。
相关问题
uniapp canvas 图片旋转
在uniapp中,可以通过canvas来实现图片旋转。具体实现方法是通过获取旋转的值,重新用canvas画图。需要在页面中加入canvas元素,并设置其高度和宽度,以便将上传的图片完整地画出来。同时,为了避免重复上传导致之前画的内容不会清空,可以使用v-if来清空。下面是一个自己封装的组件中的代码片段,可以供参考:
```html
<template>
<div class="canvas-wrap">
<canvas ref="canvas" :width="canvasWidth" :height="canvasHeight"></canvas>
</div>
</template>
<script>
export default {
data() {
return {
canvasWidth: 0,
canvasHeight: 0,
img: null,
rotate: 0
};
},
mounted() {
this.initCanvas();
},
methods: {
initCanvas() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
const img = new Image();
img.src = 'your-image-url';
img.onload = () => {
this.canvasWidth = img.width;
this.canvasHeight = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
this.rotateImage(ctx, img, this.rotate);
};
},
rotateImage(ctx, img, degree) {
const radian = degree * Math.PI / 180;
const canvas = this.$refs.canvas;
const newWidth = Math.abs(img.width * Math.cos(radian)) + Math.abs(img.height * Math.sin(radian));
const newHeight = Math.abs(img.width * Math.sin(radian)) + Math.abs(img.height * Math.cos(radian));
canvas.width = newWidth;
canvas.height = newHeight;
ctx.translate(newWidth / 2, newHeight / 2);
ctx.rotate(radian);
ctx.drawImage(img, -img.width / 2, -img.height / 2, img.width, img.height);
}
}
};
</script>
<style>
.canvas-wrap {
position: relative;
height: 100vh;
width: 100vw;
overflow: hidden;
}
</style>
```
canvas绘制图片旋转
要在canvas上绘制旋转后的图片,可以使用以下步骤:
1. 创建一个Image对象并加载要绘制的图片。
2. 在canvas上创建一个2D上下文。
3. 使用上下文的`translate()`方法将绘图原点移动到图片中心。
4. 使用上下文的`rotate()`方法旋转画布。
5. 使用上下文的`drawImage()`方法绘制图片。
以下是示例代码:
```javascript
// 创建一个Image对象并加载图片
var img = new Image();
img.src = 'path/to/image.png';
// 在canvas上创建2D上下文
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// 等待图片加载完成
img.onload = function() {
// 将绘图原点移动到图片中心
ctx.translate(canvas.width/2, canvas.height/2);
// 旋转画布
ctx.rotate(Math.PI/4); // 旋转45度
// 绘制图片
ctx.drawImage(img, -img.width/2, -img.height/2);
}
```
注意,`rotate()`方法接收的参数是弧度而不是角度,所以需要将角度转换为弧度。在本例中,我们旋转了45度,所以我们将`Math.PI/4`传递给`rotate()`方法。