0

Heys guys,

I am testing some stuff out with the native accelometer on my android phone, I want to draw rectangles, which works but I want them to be a different color everytime one is drawn.

Thank you in advance :)

    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!');
}
B.Wesselink
  • 63
  • 12

4 Answers4

0

fillStyle should have random color instead of '#FF0000'

You can use random color by 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!');
}

Edit: As suggested by Morten Olsen, provided approach may fail sometimes, You can refer this SO answer

Community
  • 1
  • 1
Rayon
  • 36,219
  • 4
  • 49
  • 76
0

Just take a function for it.

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>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Assign a random color to fillStyle.

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

From this post

Community
  • 1
  • 1
Divyesh Savaliya
  • 2,692
  • 2
  • 18
  • 37
0

Use this:

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

For more information: http://www.paulirish.com/2009/random-hex-color-code-snippets/

Roy
  • 1,939
  • 1
  • 14
  • 21