Vue - canvas 动画的常见做法是什么?
Vue - What is the common practice for canvas animation?
我想知道我的方法是否是在 Vue.js
中绘制 canvas 动画的好方法
它有效,但我不确定我做对了。
因为我使用 javascript Class 来制作 Canvas 的圆形阵列,我为此制作了一个单独的 javascript 文件并导入。 (必须将 2d 上下文传递给 class)
方法如下
Canvas.vue
<template>
<div>
<canvas id='myCanvas' width='500' height='500'></canvas>
</div>
</template>
<script>
import Circle from './canvasClass/Circle.js';
export default {
data(){
return {
canvas:null,
x:null,
y:null,
circleArr:[]
}
},
mounted(){
let canvas = document.querySelector('#myCanvas');
this.canvas = canvas.getContext('2d');
},
created(){
window.addEventListener('click',this.createCircle)
this.draw()
},
unmounted() {
window.removeEventListener('click', this.createCircle)
},
methods:{
createCircle(e){
this.circleArr.push(
new Circle(e.offsetX,e.offsetY,this.canvas)
)
},
draw(){
window.requestAnimationFrame(this.draw);
this.circleArr.forEach((d)=>{
d.animate()
})
}
}
}
</script>
圆 class 的单独 javscript 文件是
export default class Circle {
constructor(xpos, ypos, context) {
this.xpos = xpos;
this.ypos = ypos;
this.context = context;
}
draw() {
this.context.beginPath();
this.context.arc(this.xpos, this.ypos, 10, 0, Math.PI * 2);
this.context.stroke();
}
move() {
this.xpos += 0.5;
this.ypos += 0.5
}
animate() {
this.draw()
this.move()
}
}
谁能告诉我我的方法是否适合在 Vue 中绘制 canvas 动画?
如果这不是一个好方法,谁能给我更好的建议?
谢谢
是的。你走对了。
不过这里有更多有用的 npm 模块
我想知道我的方法是否是在 Vue.js
中绘制 canvas 动画的好方法它有效,但我不确定我做对了。
因为我使用 javascript Class 来制作 Canvas 的圆形阵列,我为此制作了一个单独的 javascript 文件并导入。 (必须将 2d 上下文传递给 class)
方法如下
Canvas.vue
<template>
<div>
<canvas id='myCanvas' width='500' height='500'></canvas>
</div>
</template>
<script>
import Circle from './canvasClass/Circle.js';
export default {
data(){
return {
canvas:null,
x:null,
y:null,
circleArr:[]
}
},
mounted(){
let canvas = document.querySelector('#myCanvas');
this.canvas = canvas.getContext('2d');
},
created(){
window.addEventListener('click',this.createCircle)
this.draw()
},
unmounted() {
window.removeEventListener('click', this.createCircle)
},
methods:{
createCircle(e){
this.circleArr.push(
new Circle(e.offsetX,e.offsetY,this.canvas)
)
},
draw(){
window.requestAnimationFrame(this.draw);
this.circleArr.forEach((d)=>{
d.animate()
})
}
}
}
</script>
圆 class 的单独 javscript 文件是
export default class Circle {
constructor(xpos, ypos, context) {
this.xpos = xpos;
this.ypos = ypos;
this.context = context;
}
draw() {
this.context.beginPath();
this.context.arc(this.xpos, this.ypos, 10, 0, Math.PI * 2);
this.context.stroke();
}
move() {
this.xpos += 0.5;
this.ypos += 0.5
}
animate() {
this.draw()
this.move()
}
}
谁能告诉我我的方法是否适合在 Vue 中绘制 canvas 动画? 如果这不是一个好方法,谁能给我更好的建议?
谢谢
是的。你走对了。
不过这里有更多有用的 npm 模块