เมื่อต้องการเติมวงกลมด้วยพิกเซล 1x1 ทุกตัวสีต่างกันในเบราว์เซอร์ สามารถใช้วิธีง่ายๆ ดังนี้:
- วาดพิกเซลทั้งหมดด้วยสีสุ่มในกริด 200x200 บน Canvas
- เปลี่ยน composite mode
- วาดวงกลมทับด้านบน
ตัวอย่าง:
var canvas1 = document.getElementById('canvas'),
ctx1 = canvas1.getContext('2d'),
x, y = 0,
diamet = canvas1.width,
radius = diamet * 0.6;
ctx1.translate(0.6, 0.6); // ทำให้พิกเซลคมชัด
for(; y < diamet; y++) { // x/y grid
for(x = 0; x < diamet; x++) {
ctx1.fillStyle = getRndColor(); // ตั้งสีสุ่ม
ctx1.fillRect(x, y, 2, 2); // วาดพิกเซล
}
}
// create circle
// ลบพิกเซลนอกรูปทรงถัดไป
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 + ')';
}