Canvas star test
by fxi
CSS
html,
body {
width: 100%;
height: 100%;
background-color: #white;
}
canvas {
margin: 2px;
}
JavaScript
var elBody = document.querySelector("body");
for (var i = 0; i < 100; i++) {
strokeStar({
elDest: elBody,
diameter: 10,
nBranch: 5,
inlet: 0.5,
progress: Math.random(),
threshold: 0.9,
color1: "#ccc",
color2: "#0096f5"
})
}
function strokeStar(c) {
var elCanvas = createHiDPICanvas(c.diameter, c.diameter);
c.elDest.appendChild(elCanvas);
var ctx = elCanvas.getContext("2d");
var color = c.progress <= c.threshold ? c.color1 : c.color2;
ctx.fillStyle = color;
ctx.strokeStyle = color;
ctx.lineWidth = 1;
ctx.lineCap = "round";
star(ctx, c.diameter / 2, c.nBranch, c.inlet, true);
ctx.globalCompositeOperation = "destination-out";
square(ctx, c.diameter, c.progress);
ctx.globalCompositeOperation = "source-over";
star(ctx, c.diameter / 2, c.nBranch, c.inlet, false);
return elCanvas;
}
function star(ctx, r, n, inlet, fill) {
ctx.save();
ctx.beginPath();
ctx.translate(r, r);
ctx.moveTo(0, 0 - r);
for (var i = 0; i < n; i++) {
ctx.rotate(Math.PI / n);
ctx.lineTo(0, 0 - (r * inlet));
ctx.rotate(Math.PI / n);
ctx.lineTo(0, 0 - r);
}
ctx.closePath();
ctx.stroke();
if (fill) {
ctx.fill();
}
ctx.restore();
}
function square(ctx, d, p) {
ctx.moveTo(0, 0);
ctx.fillRect(0, 0, d - d * p, d);
}
function getPixelRatio() {
if (!window.PIXEL_RATIO) {
var ctx = document.createElement("canvas").getContext("2d"),
dpr = window.devicePixelRatio || 1,
bsr = ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
ctx.backingStorePixelRatio || 1;
window.PIXEL_RATIO = dpr / bsr;
}
return window.PIXEL_RATIO
}
function createHiDPICanvas(w, h, ratio) {
//https://stackoverflow.com/questions/15661339/how-do-i-fix-blurry-text-in-my-html5-canvas
if (!ratio) {
ratio = getPixelRatio()
}
var can = document.createElement("canvas");
can.width = w *...