在 HTML5 画布上绘制一个填充有随机颜色的正方形的圆
当我们需要用不同颜色以像素为单位填充浏览器中的一个圆形时,我们可以采用这样一个简单的方法:
- 在画布上的 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 + ')';
}
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP