向生成的行添加随机颜色

时间:2014-02-19 19:33:23

标签: 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.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);

我希望它能够使每个生成的行每次都是不同的随机颜色,所以我尝试使用ctx.color但它似乎不适用于生成的行,而只是保持默认颜色为黑色。它看起来完全是在跳过它。当我打印它时,脚本似乎甚至没有开始...... 但我的ctx.color不起作用,我不明白为什么.. 请帮忙 感谢。

2 个答案:

答案 0 :(得分: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();
}

你会有一个意想不到的结果(我让你发现),但它应该可以帮助你更多地了解画布:)

答案 1 :(得分:0)

使用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();
}

要绘制线条,请使用此代替arc()

ctx.moveTo(x1, y1);  /// replace x and y with your positions
ctx.lineTo(x2, y2);
ctx.stroke();

将间隔时间增加至少16毫秒

window.setInterval(function() {
    animateCircle(position);
    position += 3;
}, 16);

或最好使用requestAnimtionFrame来获得更流畅的动画:

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