我正在使用画布为音频创建波形图形均衡器。我注意到画布上的所有像素都受到我对画布特定部分所做的笔触的影响。如果我对画布的某个区域进行更改,我希望画布的其他区域不受影响,但我的期望没有得到满足。为什么?谢谢。const c = document.getElementById('c');const ctx = c.getContext('2d');const [ r,g,b ] = [0,0,0];const { height } = ctx.canvas;const colorNode = document.getElementById('color');const narrationNode = document.getElementById('narration');var x = 0;ctx.lineWidth = 1;const interval = setInterval(() => { x++; if (x > 500) clearInterval(interval); narrationNode.innerHTML = narration.map( (narrative, i) => narrative && x >= i ? `<li>${narrative}</li>` : '' ).join(''); const margin = x/5; const gradient = ctx.createLinearGradient( 0, margin, 0, height-margin ); gradient.addColorStop(0, `rgba(${r},${g},${b},0)`); gradient.addColorStop(0.5, `rgba(${r},${g},${b},1)`); gradient.addColorStop(1.0, `rgba(${r},${g},${b},0)`); ctx.strokeStyle = gradient; ctx.moveTo(x, margin); ctx.lineTo(x, height-margin); ctx.stroke(); var pixel = ctx.getImageData(25, 5, 1, 1).data; var rgba = 'rgba(' + pixel[0] + ', ' + pixel[1] + ', ' + pixel[2] + ', ' + (pixel[3] / 255) + ')'; colorNode.innerHTML = rgba + ', ' + x;},90)
1 回答
Helenr
TA贡献1780条经验 获得超3个赞
您只缺少一个beginPath,请参阅下面的代码
const c = document.getElementById('c');
const ctx = c.getContext('2d');
const { height } = ctx.canvas;
var x = 0;
const interval = setInterval(() => {
x += 2;
if (x > 500) clearInterval(interval);
margin = x/5;
gradient = ctx.createLinearGradient(0, margin, 0, height-margin);
gradient.addColorStop(0, `rgba(0,0,0,0)`);
gradient.addColorStop(0.5, `rgba(0,0,0,1)`);
gradient.addColorStop(1.0, `rgba(0,0,0,0)`);
ctx.strokeStyle = gradient;
ctx.beginPath();
ctx.moveTo(x, margin);
ctx.lineTo(x, height-margin);
ctx.stroke();
},10)
<canvas id="c" height="100" width="500"></canvas>
添加回答
举报
0/150
提交
取消