我正在尝试制作类似于本文底部效果的文字效果
我建议的方法是:
- 制作两张画布,一张是可见的,另一张是不可见的,我用它作为缓冲区。
- 在缓冲区画布上绘制一些文本
- 循环 getImageData 像素
- 如果像素 alpha 不等于 0(当在画布缓冲区上绘制了一个像素时),有很小的机会,即 2%,则在可见画布上的该像素处绘制一个随机生成的具有酷炫效果的圆圈。
我在第 4 步遇到了麻烦。使用下面的代码,我试图在第二个画布上复制全红色的文本。相反,我得到了这张奇怪的图片。
代码
// create the canvas to replicate the buffer text on.
var draw = new Drawing(true);
var bufferText = function (size, textFont) {
// set the font to Georgia if it isn't defined
textFont = textFont || "Georgia";
// create a new canvas buffer, true means that it's visible on the screen
// Note, Drawing is a small library I wrote, it's just a wrapper over the canvas API
// it creates a new canvas and adds some functions to the context
// it doesn't change any of the original functions
var buffer = new Drawing(true);
// context is just a small wrapper library I wrote to make the canvas API a little more bearable.
with (buffer.context) {
font = util.format("{size}px {font}", {size: size, font: textFont});
fillText("Hi there", 0, size);
}
// get the imagedata and store the actual pixels array in data
var imageData = buffer.context.getImageData(0, 0, buffer.canvas.width, buffer.canvas.height);
var data = imageData.data;
var index, alpha, x, y;
// loop over the pixels
for (x = 0; x < imageData.width; x++) {
for (y = 0; y < imageData.height; y++) {
index = x * y * 4;
alpha = data[index + 3];
// if the alpha is not equal to 0, draw a red pixel at (x, y)
if (alpha !== 0) {
with (draw.context) {
dot(x/4, y/4, {fillColor: "red"})
}
}
}
}
};
bufferText(20);
请注意,在这里,我的缓冲区实际上是可见的,以显示红色像素应该去的地方与它们实际去的地方相比。
我真的对这个问题感到困惑。
如果有人知道另一种方法,那也非常受欢迎。