Canvas How to - Create sunshine effect








Question

We would like to know how to create sunshine effect.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!-- ww w.  jav a 2  s . c  om-->
function setSunBg(canvasId, n) {
    var bgCanvas = document.getElementById(canvasId);
    var width = parseInt(bgCanvas.getAttribute('width'), 10);
    var height = parseInt(bgCanvas.getAttribute('height'), 10);
    var cx = width / 2;
    var cy = height / 2;
    if (bgCanvas && bgCanvas.getContext) {
        var context = bgCanvas.getContext('2d');
        if (context) {
            var grd = context.createRadialGradient(cx, cy, 0, cx, cy, cy);
            grd.addColorStop(0, '#ffe');
            grd.addColorStop(0.3, '#ff8');
            grd.addColorStop(0.4, '#ff5');
            //grd.addColorStop(0.4, '#ff0');
            grd.addColorStop(1, '#fd0');
            context.fillStyle = grd;
            context.fillRect(0, 0, width, height);
            for (i = 1; i <= n; i += 2) {
                context.beginPath();
                context.moveTo(cx, cy)
                context.arc(cx, cy, Math.sqrt(Math.pow(cx, 2) + Math.pow(cy, 2)), 2 / n * Math.PI * (i - 1), 2 / n * Math.PI * i, false);
                context.lineTo(cx, cy)
                context.fillStyle = 'rgba(255,121,0,0.3)';
                context.fill();
                context.closePath();
            }
        }
    }
}
setSunBg('bg', 60);
}//]]>  
</script>
</head>
<body>
    <canvas id="bg" width="800" height="800"></canvas>

</body>
</html>

The code above is rendered as follows: