2

この記事の最後にある効果と同様のテキスト効果を作成しようとしています。

ここに画像の説明を入力

私の提案するアプローチは次のとおりです。

  1. 2 つのキャンバスを作成します。1 つが表示され、もう 1 つが非表示になります。これをバッファーとして使用します。
  2. バッファ キャンバスにテキストを描画する
  3. getImageData ピクセルのループ
  4. ピクセル アルファが 0 に等しくない場合 (キャンバス バッファにピクセルが描画されている場合)、わずかな確率 (つまり 2%) で、表示されているキャンバス上のそのピクセルにクールな効果を持つランダムに生成された円を描画します。

ステップ 4 で問題が発生しました。以下のコードを使用して、2 番目のキャンバスのテキストを真っ赤に複製しようとしています。代わりに、この奇妙な画像が表示されます。

結果

コード

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

ここでは、赤いピクセルが実際に移動する場所と比較して移動するはずの場所を示すために、私のバッファが実際に表示されていることに注意してください。

私はこの問題に本当に混乱しています。

誰かが別のアプローチを知っていれば、それも大歓迎です。

4

1 に答える 1

1

これを交換して...

index = x * y * 4;

と...

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

残りは良いです:)

于 2014-06-07T14:43:42.003 に答える