vue 特效类的和 canvas

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue.js结合Canvas可以实现很多炫酷的特效,下面给你一个简单的彩带特效实现代码: 1. 首先,在Vue组件中定义一个canvas元素和一个用于存储彩带的数组: ```html <template> <div> <canvas ref="canvas"></canvas> </div> </template> <script> export default { data() { return { ribbons: [] } }, mounted() { this.setupCanvas() this.animate() }, methods: { setupCanvas() { const canvas = this.$refs.canvas this.ctx = canvas.getContext('2d') canvas.width = window.innerWidth canvas.height = window.innerHeight }, animate() { requestAnimationFrame(this.animate) this.update() this.draw() }, update() { if (Math.random() > 0.97) { this.ribbons.push(new Ribbon(this.ctx)) } this.ribbons.forEach((ribbon, i) => { ribbon.update() if (ribbon.y > window.innerHeight + ribbon.height) { this.ribbons.splice(i, 1) } }) }, draw() { this.ctx.clearRect(0, 0, window.innerWidth, window.innerHeight) this.ribbons.forEach(ribbon => ribbon.draw()) } } } class Ribbon { constructor(ctx) { this.ctx = ctx this.width = Math.random() * 80 + 40 this.height = Math.random() * 150 + 100 this.x = Math.random() * window.innerWidth this.y = -this.height this.speed = Math.random() * 5 + 2 this.color = `hsl(${Math.random() * 360}, 70%, 70%)` this.angle = Math.random() * 360 this.angleSpeed = Math.random() * 4 - 2 } update() { this.y += this.speed this.angle += this.angleSpeed } draw() { this.ctx.save() this.ctx.translate(this.x, this.y) this.ctx.rotate(this.angle * Math.PI / 180) const gradient = this.ctx.createLinearGradient(-this.width / 2, 0, this.width / 2, 0) gradient.addColorStop(0, 'transparent') gradient.addColorStop(0.5, this.color) gradient.addColorStop(1, 'transparent') this.ctx.fillStyle = gradient this.ctx.fillRect(-this.width / 2, 0, this.width, this.height) this.ctx.restore() } } </script> ``` 2. 在mounted钩子函数中,调用setupCanvas()方法设置canvas的宽度和高度,并获取2D绘图上下文对象ctx。 3. 在animate()方法中,使用requestAnimationFrame()不断更新和绘制画面。在update()方法中,如果Math.random() > 0.97,就往ribbons数组中添加一个新的Ribbon对象;同时遍历ribbons数组中的每个Ribbon对象,调用它们的update()方法,更新它们的位置和角度;如果某个Ribbon对象已经超出了屏幕的下边界,就把它从数组中删除。在draw()方法中,先调用ctx.clearRect()清空画布,再遍历ribbons数组中的每个Ribbon对象,调用它们的draw()方法,绘制它们的彩带。 4. Ribbon是一个彩带对象,它的构造函数中初始化了它的位置、颜色、大小和运动速度等属性,在update()方法中更新它的位置和角度,在draw()方法中绘制它的彩带。具体来说,Ribbon对象的彩带是一个渐变矩形,渐变颜色从透明到彩色再到透明,矩形的中心点在Ribbon对象的位置,矩形的宽度和高度分别是Ribbon对象的width和height属性,矩形的旋转角度是Ribbon对象的angle属性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值