ctx交替。使用requestAnimationFrame()時使用strokeStyle
P粉605385621
2023-08-01 16:06:12
<p>我試圖繪製簡單的隨機運動作為我的登陸頁面的背景畫布,我很難讓線條具有獨特的顏色。 <br /><br />我也試過在電影之後改變它,但沒有成功(只是看起來是混合的顏色)。 </p><p><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;
}
const colors = [
'#FF1493', // Pink
'#FF00FF', // Magenta
'#800080', // Purple
'#4B0082', // Indigo
'#0000FF', // Blue
'#00FFFF', // Cyan
'#00FF00', // Green
'#FFFF00', // Yellow
'#FF7F00', // Orange
'#8B4513' // Saddle Brown
];
function drawRandomWalk(stPoint, steps) {
ctx.globalAlpha = 0.01;
let stepCount = 0;
ctx.beginPath();
ctx.strokeStyle = stPoint.color;
ctx.moveTo(stPoint.x, stPoint.y);
setTimeout(drawStep, 10);
function drawStep() {
if (stepCount >= steps) {
return;
}
ctx.moveTo(stPoint.x, stPoint.y);
const direction = Math.random() < 0.5 ? -1 : 1;
stPoint.y = stepSize * direction;
stPoint.x = startX stepCount * 2;
ctx.lineTo(stPoint.x, stPoint.y);
ctx.lineWidth = 1;
ctx.stroke();
stepCount ;
requestAnimationFrame(drawStep);
}
}
for(const color of colors)
{
const startPoint = new Point(color);
drawRandomWalk(startPoint, numSteps);
}</pre>
<pre class="brush:html;toolbar:false;"><canvas id="myCanvas" width="600" height="600"></canvas></pre>
<p><br /></p>
問題是,繪製線條的每一支「筆」都是共享狀態的——你正在繪製一條由許多移動/線條組成的長路徑,一遍又一遍。
如果您想要globalAlpha漸變效果(它依賴於能夠一遍又一遍地繪製線條),您需要分別追蹤每個筆繪製的軌跡,並繪製它,如下所示。
我去掉了Point結構,因為它不是真正需要的。
#