canvas滚动 vue_使用canvas实现一个vue弹幕组件功能

看B站时,对弹幕的实现产生了兴趣,一开始想到用css3动画去实现,后来感觉这样性能不是很好,查了下资料,发现可以用canvas实现,于是就摸索着写了一个简单的弹幕。

弹幕功能

支持动态添加弹幕

弹幕不重叠

自定义弹幕颜色

效果图

前端框架选了比较熟悉的vuejs

弹幕滚动的基本思路就是通过定时器不断地改变弹幕的位置,时时重绘画布。

实现步骤

先加入一个canvas标签,这里有个注意点,关于设备像素比对canvas的影响,会出现绘图模糊。

// 如果单纯这样写,canvas会出现模糊

//为了不出现模糊,需要设置canvas的css宽高为上下文宽高的1/devicePixelRatio,

本文是对于devicePixelRatio:2的设备设置的,该值可从window.devicePixelRatio取得。

// 后面会用到

我们先定义一个数组来存放弹幕数据,一条弹幕信息,包括文本内容,x,y坐标位置,颜色,速度(可以是随机或者固定,为了计算简单,我们这里采用了固定的速度)

var dmArr = [];

var gap = 80; // 弹幕的上下间距

var hiddenCanvas = this.$refs.hiddenCanvas;

// 增加弹幕的方法

function pushDm(text, color) {

l

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,可以先在template添加一个canvas标签,然后钩子函数获取该标签并设置画布大小和绘制笔刷等属性。接着可以监听鼠标或触摸事件,在相应的事件处理函数获取鼠标或触摸点坐标,并在画布上绘制路径。最后可以添加清空按钮,通过清空画布达到重新签名的效果。具体代码实现可以参考以下示例: ```html <template> <div> <canvas ref="canvas" @mousedown="startDrawing" @touchstart="startDrawing" @mousemove="drawing" @touchmove="drawing" @mouseup="stopDrawing" @touchend="stopDrawing" :width="width" :height="height" style="border: 1px solid #ccc;"></canvas> <button @click="clear">清空</button> </div> </template> <script> export default { data() { return { ctx: null, isDrawing: false, lineWidth: 2, strokeStyle: '#333', width: 300, height: 150 } }, mounted() { const canvas = this.$refs.canvas this.ctx = canvas.getContext('2d') this.ctx.lineJoin = 'round' this.ctx.lineCap = 'round' this.ctx.lineWidth = this.lineWidth this.ctx.strokeStyle = this.strokeStyle }, methods: { startDrawing(event) { event.preventDefault() this.isDrawing = true this.ctx.beginPath() const pos = this.getMousePosition(event) this.ctx.moveTo(pos.x, pos.y) }, drawing(event) { event.preventDefault() if (this.isDrawing) { const pos = this.getMousePosition(event) this.ctx.lineTo(pos.x, pos.y) this.ctx.stroke() } }, stopDrawing(event) { event.preventDefault() this.isDrawing = false }, clear() { this.ctx.clearRect(0, 0, this.width, this.height) }, getMousePosition(event) { const canvas = event.target const rect = canvas.getBoundingClientRect() const scaleX = canvas.width / rect.width const scaleY = canvas.height / rect.height return { x: (event.clientX - rect.left) * scaleX, y: (event.clientY - rect.top) * scaleY } } } } </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值