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

2020-04-21 07:13:45易采站长站整理

指定颜色

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

JavaScript Code复制内容到剪贴板

ctx.strokeStyle = color   

指定绘制线的颜色:

JavaScript Code复制内容到剪贴板

ctx.fillStyle = color   

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

JavaScript

JavaScript Code复制内容到剪贴板

onload = function() {   
  draw();   
};   
function draw() {   
  var canvas = document.getElementById(‘c1’);   
  if ( ! canvas || ! canvas.getContext ) { return false; }   
  var ctx = canvas.getContext(‘2d’);   
  ctx.beginPath();   
  ctx.fillStyle = ‘rgb(192, 80, 77)’; // 红   
  ctx.arc(70, 45, 35, 0, Math.PI*2, false);   
  ctx.fill();   
  ctx.beginPath();   
  ctx.fillStyle = ‘rgb(155, 187, 89)’; // 绿   
  ctx.arc(45, 95, 35, 0, Math.PI*2, false);   
  ctx.fill();   
  ctx.beginPath();   
  ctx.fillStyle = ‘rgb(128, 100, 162)’; // 紫   
  ctx.arc(95, 95, 35, 0, Math.PI*2, false);   
  ctx.fill();   
}  

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

指定透明度

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

JavaScript

JavaScript Code复制内容到剪贴板

onload = function() {   
  draw();   
};   
function draw() {   
  var canvas = document.getElementById(‘c1’);   
  if ( ! canvas || ! canvas.getContext ) { return false; }   
  var ctx = canvas.getContext(‘2d’);   
  ctx.beginPath();   
  ctx.fillStyle = ‘rgba(192, 80, 77, 0.7)’; //   
  ctx.arc(70, 45, 35, 0, Math.PI*2, false);