uniapp canvas 图片旋转
时间: 2023-11-16 13:07:47 浏览: 390
在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>
```