Canvas How to - Create Random color








Question

We would like to know how to create Random color.

Answer


<!--  w ww  .jav a  2s.  co  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.4.4.min.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(function(){
    function redraw() {
        var cc = c.getContext("2d");
        c.width = c.clientWidth;
        c.height = c.clientHeight;
        cc.scale(c.width, c.height);
        cc.fillStyle = randomColor();
        cc.beginPath();
        cc.arc(0.5, 0.5, .5, 0, 2*Math.PI);
        cc.fill();
    }
    function randomColor() {
        return '#' + Math.floor(Math.random()*0xffffff).toString(16);
    }
    window.addEventListener("resize", redraw);
    redraw();
});//]]>  
</script>
</head>
<body>
  <canvas id="c"></canvas>
</body>
</html>

The code above is rendered as follows: