Canvas How to - Set fill style using string color name








Question

We would like to know how to set fill style using string color name.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<style type='text/css'>
#canvas1 {<!--  w  w  w.  j  av  a 2 s  .  c om-->
    border: 1px solid black;
}
  </style>
<script type='text/javascript'>
$(window).load(function(){
    var can = document.getElementById('canvas1');
    var ctx = can.getContext('2d');
    ctx.fillRect(50,50,50,50);
    ctx.fillStyle = 'red';
    ctx.fillRect(150,250,20,60);
});
</script>
</head>
<body>
  <canvas id="canvas1" width="500" height="500"></canvas>
</body>
</html>

The code above is rendered as follows: