【发布时间】:2018-05-17 11:13:10
【问题描述】:
我试图在我的 web 应用上插入背景动画,但我遇到了这个消息错误。
Cannot set property 'width' of null
我的网络应用在 Vue JS 2 上。我创建了一个模板标签,里面有一个画布标签
<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>
它似乎无法识别 javascript 方法,如 width、getContext 甚至 clearRect。
感谢您的帮助。
【问题讨论】:
-
您的代码将在模块编译期间运行,甚至在远程开始出现在文档中之前。您真的想将其添加到 Vue lifecycle hooks 之一,例如
mounted -
嗨菲尔,谢谢你,我现在看得更清楚了。 5*
标签: javascript animation ecmascript-6 vuejs2