Javascript 如何每n秒更改画布上圆圈的颜色?

Javascript 如何每n秒更改画布上圆圈的颜色?,javascript,html5-canvas,Javascript,Html5 Canvas,阴影的大小是如何每n秒改变一次的?我想你必须不断地创造一个新的循环,并消除以前的循环?如何做到这一点?还有,难道没有更好的方法吗 函数main(){ var canvas=document.getElementsByTagName(“画布”)[0], ctx=canvas.getContext(“2d”); canvas.width=window.innerWidth; canvas.height=document.documentElement.scrollHeight; var cW=画布

阴影的大小是如何每n秒改变一次的?我想你必须不断地创造一个新的循环,并消除以前的循环?如何做到这一点?还有,难道没有更好的方法吗

函数main(){
var canvas=document.getElementsByTagName(“画布”)[0],
ctx=canvas.getContext(“2d”);
canvas.width=window.innerWidth;
canvas.height=document.documentElement.scrollHeight;
var cW=画布宽度,
cH=画布高度;
ctx.fillStyle=“#000”;
ctx.fillRect(0,0,cW,cH);
ctx.fill();
ctx.beginPath();
ctx.fillStyle=“#FFF”;
ctx.shadowBlur=5;
ctx.shadowColor=“#FFF”;
ctx.arc(cW/2,cH/2,50,0,2*Math.PI,假);
ctx.fill();
ctx.closePath();
}
window.addEventListener(“加载”,主)

JS-Bin

创建一个
setInterval
颜色数组。使用
Math.random
随机选择任何颜色。 修改
main
函数以接受颜色作为两个参数

function main(bckColor、circleColor){
var canvas=document.getElementsByTagName(“画布”)[0],
ctx=canvas.getContext(“2d”);
if(画布高度){
canvas.height=0;
}
canvas.width=window.innerWidth;
canvas.height=document.documentElement.scrollHeight;
var cW=画布宽度,
cH=画布高度;
ctx.fillStyle=bckColor | |“#000”;
//ctx.fillStyle=“红色”;
ctx.fillRect(0,0,cW,cH);
ctx.fill();
ctx.beginPath();
ctx.fillStyle=circleColor | |“#FFF”;
ctx.shadowBlur=5;
ctx.shadowColor=“#FFF”;
ctx.arc(cW/2,cH/2,50,0,2*Math.PI,假);
ctx.fill();
ctx.closePath();
}
var colorArray=[“红色”、“绿色”、“黄色”、“蓝色”、“粉色”、“棕色”、“橙色”]
var changeColor=setInterval(函数(){
设bckColor=colorArray[Math.floor(Math.random()*7+1)];
设circleColor=colorArray[Math.floor(Math.random()*7+1)];
主色(bckColor、圆环色)
}, 2000)
window.addEventListener(“加载”,主)

我建议使用覆盖,创建一个圆div,将其放置在画布的圆上,并使用css设置其阴影的动画,而不是每x秒重新绘制画布本身的动画,您将拥有所有想要的控件,如阴影的颜色和距离、动画速度等等

这是一个(覆盖层的位置更好)

函数main(){
var canvas=document.getElementsByTagName(“画布”)[0],
ctx=canvas.getContext(“2d”);
canvas.width=window.innerWidth;
canvas.height=document.documentElement.scrollHeight;
var cW=画布宽度,
cH=画布高度;
ctx.fillStyle=“#000”;
ctx.fillRect(0,0,cW,cH);
ctx.fill();
ctx.beginPath();
ctx.fillStyle=“#FFF”;
ctx.shadowBlur=5;
ctx.shadowColor=“#FFF”;
ctx.arc(cW/2,cH/2,50,0,2*Math.PI,假);
ctx.fill();
ctx.closePath();
//将覆盖层放置在圆上
overlay.style.top=(cH/2-99)+“px”
overlay.style.left=(cW/2-50)+“px”
}
window.addEventListener(“加载”,主);
main()
常数animationDuration=2;
函数getRandomColor(){
变量字母='0123456789ABCDEF';
var color='#';
对于(变量i=0;i<6;i++){
颜色+=字母[Math.floor(Math.random()*16)];
}
返回颜色;
}
overlay.style.animationDuration=animationDuration+'s';
setInterval(函数(){
overlay.style.color=getRandomColor()
},动画持续时间*1000)
*{
框大小:边框框;
保证金:0;
填充:0;
}
帆布{
宽度:100vw;
高度:100vh;
显示:块;
}
#覆盖层{
边界半径:50%;
背景:无;
动画:阴影线性无限;
保证金:自动;
转换:翻译(0,50%);
颜色:绿色;
位置:绝对位置;
z指数:99;
宽度:100px;
高度:93px;
}
@关键帧阴影{
0% 100% {
框阴影:0
}
50% {
长方体阴影:0 50像素20像素
}
}


您还需要更新阴影模糊吗?如果是,是的,重新绘制。。。否则,请使用。您是否绝对希望使用画布?你能将div与css结合使用吗?只有canvas,没有cssIs这是最佳的吗?无限地画圆圈?我怎样才能抹去旧的圆圈?哦,没有特别的原因,我想我只是把它忘在那里了。。这里有一把小提琴只叫它一次