<template>
<canvas ref="myCanvas"></canvas>
</template>
<script>
export default {
mounted() {
this.$nextTick(() => {
this.loadImage();
});
},
methods: {
loadImage() {
const canvas = this.$refs.myCanvas;
const ctx = canvas.getContext('2d');
const image = new Image();
image.src = 'path/to/your/image.jpg'; // 将"path/to/your/image.jpg"替换为你的图片路径
image.onload = () => {
const scale = 0.5; // 设置缩放比例为0.5,即缩小一半
const scaledWidth = image.width * scale; // 缩放后的宽度
const scaledHeight = image.height * scale; // 缩放后的高度
canvas.width = scaledWidth; // 设置Canvas宽度为缩放后的宽度
canvas.height = scaledHeight; // 设置Canvas高度为缩放后的高度
ctx.drawImage(image, 0, 0, scaledWidth, scaledHeight); // 绘制缩放后的图片
const rectangles = [
{ x: 50, y: 50, width: 100, height: 100 },
{ x: 200, y: 100, width: 150, height: 80 },
// 添加更多的矩形对象
];
ctx.strokeStyle = 'red'; // 设置边框颜色
ctx.lineWidth = 1; // 设置线条宽度为1
ctx.setLineDash([2, 2]); // 设置虚线样式,[2, 2]表示实线长度为2,空白长度为2
for (let i = 0; i < rectangles.length; i++) {
const rect = rectangles[i];
ctx.strokeRect(
rect.x * scale,
rect.y * scale,
rect.width * scale,
rect.height * scale
); // 使用缩放后的尺寸绘制边框
}
};
},
},
};
</script>
canvas加载图片缩小比例显示并标注矩形区域(vue)
于 2023-06-07 11:04:20 首次发布