我正在尝试使用 canvas 元素在浏览器中创建一个基本的频闪灯。我期待 setInterval 继续调用 changeBG 函数以更改为随机背景颜色。这个函数本身就可以正常工作,但当被 setInterval 调用时就不行了。我尝试在萤火虫中拉出此页面,它告诉我颜色未定义。这是有问题的代码。
<html>
<head>
<title>Strobe!</title>
<link rel="stylesheet" type="text/css" href="reset.css" />
<script type="text/javascript">
function changeBG(colors,ctx,canvas) {
ctx.fillStyle = colors[Math.floor(Math.random()*colors.length)]
ctx.fillRect(0,0,canvas.width,canvas.height)
}
function eventLoop() {
var colors = ['#000000','#ff0000','#00ff00','#0000ff','#ffff00','#ff00ff','#00ffff']
var canvas = document.getElementById('mainCanvas')
var ctx = canvas.getContext('2d')
canvas.width = window.innerWidth
canvas.height = window.innerHeight
//changeBG(colors,ctx,canvas)
setInterval("changeBG(colors,ctx,canvas)", 1000);
}
</script>
</head>
<body onload="eventLoop()">
<canvas id="mainCanvas" width="800" height="600">
</canvas>
</body>
我是 javascript 的新手,所以任何洞察力都会受到高度赞赏。