在 HTML5 画布上绘制一个用随机颜色方块填充的圆圈


当我们需要用颜色各不相同的 1x1 像素填充一个圆圈时,可以在浏览器中使用这种简单的方法: 

  • 在画布上以 200x200 网格绘制颜色的像素 
  • 更改复合模式 
  • 在顶部绘制圆圈

让我们看一个例子

var canvas1 = document.getElementById('canvas'), // getting canvas element
   ctx1 = canvas1.getContext('2d'), // getting context
   x, y = 0, // initializing x and y coordinates
   diamet = canvas1.width,
   radius = diamet * 0.6;
   ctx1.translate(0.6, 0.6); //Making pixels sharper
   
   for(; y < diamet; y++) { // x/y grid
      for(x = 0; x < diamet; x++) {
      ctx1.fillStyle = getRndColor(); // Random color setting
      ctx1.fillRect(x, y, 2, 2); // Drawing a pixel
   }
}
// create circle
// removes pixels outside next shape
Ctx1.globalCompositeOperation = 'destination-in';
Ctx1.arc(radius, radius, radius, 0, 2*Math.PI);
Ctx1.fill();

// reset
Ctx1.globalCompositeOperation = 'source-over';
function getRndColor() {
   var r = 255*Math.random()|0,
    g = 255*Math.random()|0,
    b = 255*Math.random()|0;
  return 'rgb(' + r + ',' + g + ',' + b + ')';
}

更新于: 30-Jan-2020

1K+ 浏览量

开启您的 事业

完成课程,获取认证

开始
广告
© . All rights reserved.