返回
将canvas动态星空融入vue3+ts,让你的星空背景更具交互性
前端
2023-06-15 23:07:19
canvas + Vue 3 + TypeScript:用代码绘制璀璨星空
前言
在数字艺术领域,canvas、Vue 3 和 TypeScript 正在掀起一场革命。它们携手打造出令人惊叹的动态体验,让我们的网页设计熠熠生辉。踏上这段奇妙的旅程,用代码点亮夜空,用创意照亮你的网页吧!
准备工作
准备工作包括:
- 安装 Node.js 和 npm。
- 创建新的 Vue 3 项目。
- 安装依赖项:
npm install vue3 canvas
构建 canvas 画布
在 Vue 组件中添加 canvas 元素:
<template>
<canvas ref="canvas" width="600px" height="600px"></canvas>
</template>
获取 canvas 上下文:
export default {
setup() {
const canvasRef = ref(null);
const ctx = canvasRef.value.getContext('2d');
return {
canvasRef,
ctx,
};
},
};
绘制星空
使用 canvas API 绘制星星:
function drawStar(ctx, x, y, radius, color) {
ctx.beginPath();
ctx.fillStyle = color;
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fill();
}
用循环绘制大量星星:
for (let i = 0; i < 500; i++) {
const x = Math.random() * canvasRef.value.width;
const y = Math.random() * canvasRef.value.height;
const radius = Math.random() * 2;
const color = `hsl(${Math.random() * 360}, 50%, 50%)`;
drawStar(ctx, x, y, radius, color);
}
添加交互性
用 Vue 3 的响应式实现鼠标移动时的星星闪烁:
<template>
<div @mousemove="onmousemove">
<canvas ref="canvas" width="600px" height="600px"></canvas>
</div>
</template>
<script>
export default {
methods: {
onmousemove(e) {
const ctx = this.ctx;
ctx.clearRect(0, 0, canvasRef.value.width, canvasRef.value.height);
for (let i = 0; i < 500; i++) {
const x = Math.random() * canvasRef.value.width;
const y = Math.random() * canvasRef.value.height;
const radius = Math.random() * 2;
const color = `hsl(${Math.random() * 360}, 50%, 50%)`;
const opacity = e.clientX / canvasRef.value.width;
drawStar(ctx, x, y, radius, `rgba(${color}, ${opacity})`);
}
},
},
};
</script>
用 TypeScript 定义类型并检查数据:
interface Star {
x: number;
y: number;
radius: number;
color: string;
}
const stars: Star[] = [];
for (let i = 0; i < 500; i++) {
stars.push({
x: Math.random() * canvasRef.value.width,
y: Math.random() * canvasRef.value.height,
radius: Math.random() * 2,
color: `hsl(${Math.random() * 360}, 50%, 50%)`,
});
}
总结
canvas、Vue 3 和 TypeScript 的强强联手,为我们打造出动态的、交互式的星空背景。无论你是前端开发者还是设计爱好者,这篇文章都将点燃你的创意,用代码照亮你的网页!
常见问题解答
-
如何调整星星的数量?
修改for
循环中的数字即可,如for (let i = 0; i < 1000; i++)
。 -
如何改变星星的顏色?
修改color
的值,例如color: 'blue'
。 -
如何添加星星的运动效果?
使用requestAnimationFrame()
函数,不断更新星星的位置。 -
如何让星星隨滑鼠移動而變化?
在onmousemove
方法中,根據滑鼠位置調整opacity
值。 -
如何使用 TypeScript 進行類型檢查?
在 TypeScript 文件中定義介面和類型,並使用它們來檢查數據類型。