Javascript 向生成的线添加随机颜色

Javascript 向生成的线添加随机颜色,javascript,canvas,random,colors,generator,Javascript,Canvas,Random,Colors,Generator,我开始学习javascript,我想给这个项目中生成的每个随机行添加一个随机颜色 var c = document.createElement('canvas'); document.body.appendChild(c); var ctx = c.getContext('2d'); c.width = window.innerWidth; c.height = window.innerHeight; var position = 0; ctx.lineWidth = window.promp

我开始学习javascript,我想给这个项目中生成的每个随机行添加一个随机颜色

var c = document.createElement('canvas');
document.body.appendChild(c);
var ctx = c.getContext('2d');
c.width = window.innerWidth;
c.height = window.innerHeight;
var position = 0;

ctx.lineWidth = window.prompt("what line width do you want?","0.5");

ctx.color = "#"+((1<<24)*Math.random()|0).toString(16);

function animateCircle(position) {
    ctx.clearRect(0,0,c.width,c.height);
    ctx.arc(c.width/2,c.height/2,(c.width > c.height ? c.height : c.width)/3,position,position+Math.random()*10,false);ctx.stroke();
}
window.setInterval(function() {
    animateCircle(position);
    position += 3;
}, 10);
var c=document.createElement('canvas');
文件.正文.附件(c);
var ctx=c.getContext('2d');
c、 宽度=window.innerWidth;
c、 高度=窗内高度;
var位置=0;
ctx.lineWidth=window.prompt(“您想要什么线宽?”,“0.5”);

ctx.color=“#”+((1你要找的是
strokeStyle
,而不是
color
。试试:

function animateCircle(position) {
    ctx.strokeStyle = "#"+((1<<24)*Math.random()|0).toString(16);
    ctx.arc(c.width/2,c.height/2,(c.width > c.height ? c.height : c.width)/3,position,position+Math.random()*10,false);
    ctx.stroke();
}
函数动画循环(位置){

ctx.strokeStyle=“#”+((1使用
strokeStyle
而不是颜色。您还将注意到以下几个问题:

function animateCircle(position) {

    ctx.strokeStyle = "#"+((1<<24)*Math.random()|0).toString(16);

    ctx.clearRect(0,0,c.width,c.height);

    /// remember beginPath() here or the arc will accumulate
    ctx.beginPath();
    ctx.arc(c.width/2,c.height/2,(c.width > c.height ? c.height : c.width)/3,position,position+Math.random()*10,false);
    ctx.stroke();
}
将间隔至少增加到16毫秒

window.setInterval(function() {
    animateCircle(position);
    position += 3;
}, 16);
或者最好使用
requestanimationframe
以获得更平滑的动画:

(function loop() {
    animateCircle(position);
    position += 3;
    requestAnimtionFrame(loop);
})();

非常感谢这是一个非常酷的效果!!:)它在整个物体上产生了疯狂的迷幻效果并改变了颜色:D但它没有达到我想要的效果:)我希望它每次都能用任何颜色划出一条线,这样我就可以把许多不同的颜色聚在一起了!但我必须说,先生,这真的很酷!!!再次感谢Hanks alot@Ken!!:)
(function loop() {
    animateCircle(position);
    position += 3;
    requestAnimtionFrame(loop);
})();