随机改变颜色Javascript

时间:2016-04-07 07:11:50

标签: javascript android cordova random colors

嘿伙计们,

我正在使用我的Android手机上的原生accelometer测试一些东西,我想绘制矩形,这有效但我希望每次绘制时它们都是不同的颜色。

提前谢谢你:)

    function onSuccess(acceleration) {

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.width = window.innerWidth;
context.height = window.innerHeight;

    context.save(); 
    context.beginPath();
    context.rect(acceleration.x*10+150, acceleration.y*10+100, acceleration.z*10, acceleration.y*10);
    context.fillStyle = '#FF0000';
    context.fill();
    context.lineWidth = 3;
    context.strokeStyle = 'black';
    context.stroke();
    context.restore(); 

}

function onError() {
    alert('onError!');
}

4 个答案:

答案 0 :(得分:0)

fillStyle应该是随机颜色而不是'#FF0000'

您可以random color

使用Paul Irish

function onSuccess(acceleration) {
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');
  context.width = window.innerWidth;
  context.height = window.innerHeight;
  context.save();
  context.beginPath();
  context.rect(acceleration.x * 10 + 150, acceleration.y * 10 + 100, acceleration.z * 10, acceleration.y * 10);
  context.fillStyle = '#' + Math.floor(Math.random() * 16777215).toString(16);
  context.fill();
  context.lineWidth = 3;
  context.strokeStyle = 'black';
  context.stroke();
  context.restore();
}

function onError() {
  alert('onError!');
}

修改:根据Morten Olsen的建议,提供的方法有时会失败,您可以参考此SO answer

答案 1 :(得分:0)

只需要一个功能。

function randomColor() {
   var c = "#";
   for (var i = 0; i < 6; i++) {
       c += (Math.random() * 16 | 0).toString(16);
   } 
   return c;
}

var a = document.getElementById("id1").style;
a.color = randomColor();
<h1 id="id1">stackoverflow</h1>

答案 2 :(得分:0)

为fillStyle指定随机颜色。

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

来自this post

答案 3 :(得分:0)

使用此:

'#'+Math.floor(Math.random()*16777215).toString(16);

有关详细信息:http://www.paulirish.com/2009/random-hex-color-code-snippets/

相关问题