我开始学习 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 不起作用,我不明白为什么.. 请帮忙 谢谢。
最佳答案
您要寻找的是行程样式
,而不是颜色
。尝试:
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();
}
你会得到一个意想不到的结果(我让你发现的),但它应该可以帮助你更多地了解 Canvas :)
关于javascript - 向生成的线条添加随机颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21890511/