我试图在我的webapp上插入我的背景动画,但我正面临此消息错误。
Cannot set property 'width' of null
我的网络应用程序在Vue JS 2上。我在
中创建了一个带有canvas标签的模板标签<template>
<canvas>
<GlobalView></GlobalView>
</canvas>
</template>
在我的脚本标签内,在导出默认方法之后,我插入了我的动画:
<script>
import GlobalView from '@/GlobalView'
export default {
name: 'App',
components: {
GlobalView
}
}
const canvas = document.querySelector('canvas')
canvas.width = window.innerWidth
canvas.height = window.innerHeight
const c = canvas.getContext('2d')
const colors = ['#E0FBFC', '#FF5964', '#FFFFFF', '#38618C', '#C2DFE3']
function Circle (x, y, r, dx, dy, color) {
this.x = x
this.y = y
this.r = r
this.dx = dx
this.dy = dy
this.draw = function () {
c.beginPath()
c.arc(this.x, this.y, this.r, 0, Math.PI * 2, false)
c.fillStyle = color
c.fill()
if (this.y + this.r >= innerHeight || this.y - this.r <= 0) {
this.dy = -this.dy
}
if (this.x + this.r >= innerWidth || this.x - this.r <= 0) {
this.dx = -this.dx
}
this.x += this.dx
this.y += this.dy
}
}
const circles = []
for (let i = 0; i < 10; i++) {
const r = (Math.random() * 30) + 10
const x = Math.random() * (innerWidth - r * 2) + r
const y = Math.random() * (innerHeight - r * 2) + r
const dx = (Math.random() - 0.5)
const dy = (Math.random() - 0.5)
const color = colors[Math.floor(Math.random() * colors.length)]
const circle = new Circle(x, y, r, dx, dy, color)
circles.push(circle)
}
const drawCircle = () => {
requestAnimationFrame(drawCircle)
c.clearRect(0, 0, innerWidth, innerHeight)
circles.forEach((circle) => {
circle.draw()
})
}
drawCircle()
canvas.addEventListener('click', (e) => {
for (let i = 0; i < 5; i++) {
const r = (Math.random() * 30) + 10
const dx = (Math.random() - 0.5)
const dy = (Math.random() - 0.5)
const color = colors[Math.floor(Math.random() * colors.length)]
circles.push(new Circle(e.pageX, e.pageY, r, dx, dy, color))
}
})
window.addEventListener('resize', () => {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
})
</script>
它似乎无法识别像width,getContext甚至clearRect这样的javascript方法。
感谢您的帮助。
答案 0 :(得分:1)
Of course it won't work, because you do not use methods and call it,
<script>
import GlobalView from '@/GlobalView'
export default {
name: 'App',
components: {
GlobalView
},
methods: {
canvas () {
const canvas = document.querySelector('canvas')
canvas.width = window.innerWidth
canvas.height = window.innerHeight
....
}
}
}
//and then, call it,, vm = new Vue()
vm.canvas();
</script>