用vue实现矩形
使用 Vue 实现矩形
在 Vue 中实现矩形可以通过多种方式完成,常见的方法包括使用 HTML/CSS 绘制、Canvas API 或 SVG。以下是几种实现方式:
使用 HTML/CSS 绘制矩形
通过 Vue 的模板和样式绑定,可以轻松创建一个矩形:

<template>
<div class="rectangle" :style="{ width: width + 'px', height: height + 'px', backgroundColor: color }"></div>
</template>
<script>
export default {
data() {
return {
width: 200,
height: 100,
color: 'blue'
};
}
};
</script>
<style>
.rectangle {
border: 2px solid black;
}
</style>
- 通过
width和height控制矩形尺寸。 - 通过
backgroundColor设置填充颜色。 - 使用
border添加边框。
使用 Canvas API 绘制矩形
Canvas 提供了更灵活的绘图能力,适合动态或交互式矩形:

<template>
<canvas ref="canvas" :width="width" :height="height"></canvas>
</template>
<script>
export default {
data() {
return {
width: 300,
height: 150,
color: 'green'
};
},
mounted() {
this.drawRectangle();
},
methods: {
drawRectangle() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
ctx.fillStyle = this.color;
ctx.fillRect(10, 10, this.width - 20, this.height - 20);
ctx.strokeStyle = 'black';
ctx.strokeRect(10, 10, this.width - 20, this.height - 20);
}
}
};
</script>
- 通过
fillRect绘制填充矩形。 - 通过
strokeRect绘制边框。 - 使用
mounted钩子确保 DOM 加载完成后绘制。
使用 SVG 绘制矩形
SVG 是矢量图形标准,适合需要缩放或动画的场景:
<template>
<svg :width="width" :height="height">
<rect
x="10"
y="10"
:width="width - 20"
:height="height - 20"
:fill="color"
stroke="black"
stroke-width="2"
/>
</svg>
</template>
<script>
export default {
data() {
return {
width: 250,
height: 120,
color: 'red'
};
}
};
</script>
- 通过
rect标签定义矩形。 - 使用
fill设置填充颜色,stroke设置边框颜色。 - SVG 支持动态属性绑定,适合与 Vue 结合。
动态调整矩形属性
通过 Vue 的响应式特性,可以动态调整矩形的尺寸、颜色等属性:
<template>
<div>
<div class="rectangle" :style="rectangleStyle"></div>
<input v-model="width" type="range" min="50" max="300">
<input v-model="height" type="range" min="50" max="300">
<input v-model="color" type="color">
</div>
</template>
<script>
export default {
data() {
return {
width: 200,
height: 100,
color: '#ff0000'
};
},
computed: {
rectangleStyle() {
return {
width: this.width + 'px',
height: this.height + 'px',
backgroundColor: this.color
};
}
}
};
</script>
- 使用
v-model绑定输入控件到数据属性。 - 通过
computed动态计算样式。
以上方法覆盖了从简单静态矩形到动态交互式矩形的实现,可以根据需求选择合适的方式。






