详解HTML5 Canvas绘制时指定颜色与透明度的方法

2019-01-28 15:00:10王旭

指定颜色

黑色是Canvas绘制的默认色彩,要想换一种颜色的话,就得在实际画之前指定颜色。

JavaScript Code复制内容到剪贴板
  1. ctx.strokeStyle = color   

指定绘制线的颜色:

JavaScript Code复制内容到剪贴板
  1. ctx.fillStyle = color   

指定填充的颜色:
来看看实际的例子:

JavaScript

JavaScript Code复制内容到剪贴板
  1. onload = function() {      draw();   
  2. };    function draw() {   
  3.   var canvas = document.getElementById('c1');      if ( ! canvas || ! canvas.getContext ) { return false; }   
  4.   var ctx = canvas.getContext('2d');      ctx.beginPath();   
  5.   ctx.fillStyle = 'rgb(192, 80, 77)'; // 红      ctx.arc(70, 45, 35, 0, Math.PI*2, false);   
  6.   ctx.fill();      ctx.beginPath();   
  7.   ctx.fillStyle = 'rgb(155, 187, 89)'; // 绿      ctx.arc(45, 95, 35, 0, Math.PI*2, false);   
  8.   ctx.fill();      ctx.beginPath();   
  9.   ctx.fillStyle = 'rgb(128, 100, 162)'; // 紫      ctx.arc(95, 95, 35, 0, Math.PI*2, false);   
  10.   ctx.fill();    }  

效果如下图:
2016325112217008.png (142×142)

指定透明度

和普通的CSS中一样,我们指定颜色的时候还可以带一个alpha值(不过用的不多,IE9之前都不支持)。看代码:

JavaScript

JavaScript Code复制内容到剪贴板
  1. onload = function() {      draw();   
  2. };    function draw() {   
  3.   var canvas = document.getElementById('c1');      if ( ! canvas || ! canvas.getContext ) { return false; }