var ctx = document.querySelector("canvas").getContext("2d"),
inp = document.querySelector("input"),
w = ctx.canvas.width,
h = ctx.canvas.height,
balls = []; // global ball array
ctx.fillStyle = "rgb(0, 154, 253)"; // fill must be a solid color
generate(inp.value) // init default text
inp.onkeyup = function() {generate(this.value)}; // get some text to demo
function generate(txt) {
var i, radius = 5, // ball radius
data32; // we'll use uint32 for speed
balls = []; // clear ball array
ctx.clearRect(0, 0, w, h); // clear canvas so we can
ctx.fillText(txt.toUpperCase(), 0, 10); // draw the text (default 10px)
// get a Uint32 representation of the bitmap:
data32 = new Uint32Array(ctx.getImageData(0, 0, w, h).data.buffer);
// loop through each pixel. We will only store the ones with alpha = 255
for(i = 0; i < data32.length; i++) {
if (data32[i] & 0xff000000) { // check alpha mask
balls.push({ // add new ball if a solid pixel
x: (i % w) * radius * 2 + radius, // use position and radius to
y: ((i/w)|0) * radius * 2 + radius, // pre-calc final position and size
radius: radius,
a: (Math.random() * 250)|0 // just to demo animation capability
});
}
}
// return array - here we'll animate it directly to show the resulting objects:
}
(function animate() {
ctx.clearRect(0, 0, w, h);
ctx.beginPath();
for(var i = 0, ball; ball = balls[i]; i++) {
var dx = Math.sin(ball.a * 0.2) + ball.radius, // do something funky
dy = Math.cos(ball.a++ * 0.2) + ball.radius;
ctx.moveTo(ball.x + ball.radius + dx, ball.y + dy);
ctx.arc(ball.x + dx, ball.y + dy, ball.radius, 0, 6.28);
ctx.closePath();
}
ctx.fill();
requestAnimationFrame(animate);
})();
body {font:bold 16px sans-serif}
<label>Type some text: <input value="PIXELS"></label><br>
<canvas width=1024></canvas>
可能重複http://stackoverflow.com/questions/19954058/html5-canvas-text-十字路口) –