Canvas How to - Change opacity through stokeStyle








Question

We would like to know how to change opacity through stokeStyle.

Answer


<!--   w w  w  .j  a  v  a  2s  . c  o m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var ctx = document.getElementById("canvas").getContext("2d");
    // horizontal lines of varying opacity
    for (var y = 0; y < 100; y += 10) {
        ctx.strokeStyle = 'rgba(' + [255, 0, 0, y / 100] + ')';
        ctx.beginPath();
        ctx.moveTo(0, y);
        ctx.lineTo(100, y);
        ctx.stroke();
    }
    // these vertical lines will be invisible
    for (var x = 0; x < 100; x += 10) {
        ctx.strokeStyle = 'rgba(' + [0, 0, 0, 0] + ')';
        ctx.beginPath();
        ctx.moveTo(x, 0);
        ctx.lineTo(x, 100);
        ctx.stroke();
    }
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" height="100" width="100" onclick="draw()"></canvas>
</body>
</html>

The code above is rendered as follows: