vue3中实现canvas 图片等比例缩放,并写出详细的代码
时间: 2023-08-31 13:06:20 浏览: 76
在Vue3中实现canvas图片等比例缩放,可以使用以下步骤:
1. 创建一个canvas元素,将其添加到DOM中。
2. 加载需要缩放的图片,并将其绘制到canvas上。
3. 获取canvas元素的宽高。
4. 计算缩放比例(即原图宽高与canvas宽高的比例),并按比例缩放图片。
5. 将缩放后的图片绘制到canvas上。
以下是详细的代码实现:
```html
<template>
<canvas ref="canvas"></canvas>
</template>
<script>
export default {
mounted() {
const canvas = this.$refs.canvas
const ctx = canvas.getContext('2d')
const img = new Image()
img.src = 'image.jpg'
img.onload = () => {
canvas.width = canvas.offsetWidth
canvas.height = canvas.offsetHeight
const scale = Math.min(canvas.width / img.width, canvas.height / img.height)
const width = img.width * scale
const height = img.height * scale
ctx.drawImage(img, (canvas.width - width) / 2, (canvas.height - height) / 2, width, height)
}
}
}
</script>
```
在上面的代码中,我们首先获取了canvas元素和其2D上下文对象ctx,然后创建一个Image对象并加载需要缩放的图片。在图片加载完成后,我们获取canvas元素的宽高,计算出缩放比例,按比例缩放图片,并将缩放后的图片绘制到canvas上。最终,我们就可以在页面上看到等比例缩放后的图片。