【问题标题】:JavaScript canvas, manually cloning a canvas onto another generates a weird patternJavaScript画布,手动将画布克隆到另一个画布上会产生奇怪的模式
【发布时间】:2014-06-07 14:12:45
【问题描述】:

我正在尝试制作类似于this article底部的效果的文字效果

我建议的方法是:

  1. 制作两张画布,一张可见,另一张不可见,我将其用作缓冲区。
  2. 在缓冲区画布上绘制一些文本
  3. 遍历 getImageData 像素
  4. 如果像素 alpha 不等于 0(当在画布缓冲区上绘制像素时),则有很小的几率(即 2%)在可见画布上的该像素处绘制一个随机生成的圆形。李>

我在第 4 步遇到了问题。使用下面的代码,我试图在第二个画布上复制全红色的文本。相反,我得到this weird picture

代码

// 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);

请注意,在这里,我的缓冲区实际上是可见的,以显示红色像素应该去的地方与它们实际去的地方相比。

我真的被这个问题弄糊涂了。

如果有人知道另一种方法,那也非常受欢迎。

【问题讨论】:

    标签: javascript html canvas text generative-art


    【解决方案1】:

    替换这个...

    index = x * y * 4;
    

    与...

    index = (imageData.width * y) + x;
    

    其余的都很好:)

    【讨论】:

    • 天哪,这很容易 x]。请注意,我还必须将 dot(x, y, {fillColor: "red"}); 替换为 dot(x/4, y/4, {fillColor: "red"});
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 2015-02-15
    • 2013-12-17
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    相关资源
    最近更新 更多