ホームページ  >  に質問  >  本文

ctx 代替。 requestAnimationFrame() を使用する場合は、ストロークスタイルを使用します。

<p>ランディング ページの背景キャンバスとして単純なランダムな動きを描画しようとしていますが、線に独自の色を付けるのに苦労しています。 <br /><br /> また、映画の後に変更しようとしましたが、成功しませんでした(混合色のように見えます)。 </p>


<p><br /></p> <pre class="brush:js;toolbar:false;">const Canvas = document.getElementById('myCanvas'); const ctx = Canvas.getContext('2d'); //ctx.canvas.width = window.innerWidth; //ctx.canvas.height = window.innerHeight*4; const numSteps = ctx.canvas.width / 2 10; const stepSize = 10; const startX = 0; const startY = Canvas.height / 2; const timeInterval = 15; var Point = function(color_inp){ this.x = startX; this.y = startY; this.color = color_inp; } 定数色 = [ '#FF1493', // ピンク '#FF00FF', // マゼンタ '#800080', // 紫 '#4B0082', // インディゴ '#0000FF', // 青 '#00FFFF', // シアン '#00FF00', // 緑 '#FFFF00', // 黄色 '#FF7F00', // オレンジ '#8B4513' // サドルブラウン ]; 関数drawRandomWalk(stPoint, ステップ) { ctx.globalAlpha = 0.01; stepCount = 0 にします。 ctx.beginPath(); ctx.ストロークスタイル = stPoint.color; ctx.moveTo(stPoint.x, stPoint.y); setTimeout(drawStep, 10); 関数drawStep() { if (stepCount >= 歩数) { 戻る; } ctx.moveTo(stPoint.x, stPoint.y); const 方向 = Math.random() < 0.5 ? -1 : 1; stPoint.y = stepSize * 方向; stPoint.x = startX ステップ数 * 2; ctx.lineTo(stPoint.x, stPoint.y); ctx.lineWidth = 1; ctx.ストローク(); ステップ数; requestAnimationFrame(drawStep); } } for(色の定数色) { const startPoint = 新しいポイント(色); drawRandomWalk(startPoint, numSteps); }</pre> <pre class="brush:html;toolbar:false;"><canvas id="myCanvas" width="600" height="600"></canvas></pre> <p><br /></p>
P粉605385621P粉605385621445日前466

全員に返信(1)返信します

  • P粉327903045

    P粉3279030452023-08-02 00:56:35

    問題は、線を描くすべての「ペン」が状態を共有していることです。つまり、多くの動き/線で構成される長いパスを何度も繰り返し描いていることになります。

    globalAlpha グラデーション効果 (線を何度も描画できることに依存します) が必要な場合は、各ペン描画を個別にトレースし、以下に示すように描画する必要があります。

    Point 構造体は実際には必要ないので削除しました。


    リーリー リーリー


    返事
    0
  • キャンセル返事