【问题标题】:adding a random color to a generated line向生成的线添加随机颜色
【发布时间】:2014-03-20 09:00:14
【问题描述】:

我开始学习 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 不起作用,我不明白为什么.. 请帮忙 谢谢。

【问题讨论】:

    标签: javascript canvas random colors generator


    【解决方案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();
    }
    

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

    【讨论】:

    • 非常感谢,这是一个非常酷的效果! :) 它正在对整个物体产生疯狂的迷幻效果并改变颜色 :D 但它并没有完成我想要它做的事情:) 我希望它每次都能以任何颜色画一条线,所以我最终会得到许多不同的颜色聚集在一起!但我不得不说先生,这真的很酷!!!再次感谢
    【解决方案2】:

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

    将间隔增加到至少 16ms

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

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

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

    【讨论】:

    • 非常感谢@Ken! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 2012-02-19
    • 2013-04-02
    • 2018-04-02
    • 2021-05-23
    • 2011-03-09
    • 2016-02-20
    相关资源
    最近更新 更多