我有下面的脚本,它在画布上绘制红色矩形,问题是矩形会随着时间的推移变得更强的不透明度。为什么?
HTML:
<canvas id="myCanvas" width="500" height="150" style="border:1px solid black;">
</canvas>
Javascript:
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
const inter = setInterval(start, 1000);
i = 0;
myarr = [];
function drawarray(arr){
for ( var k = 0; k<arr.length; k++){
// I tried to use Math random, but it also don't work
// I tried rgba, but also don't work
ctx.globalAlpha = 0.2;
ctx.fillStyle = "red";
ctx.fillRect(canvas.width-90-i*50,arr[k][0]*5,10,2);
}
}
function start() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for ( var e=0; e<10;e++){
myarr.push([e,Math.random().toFixed(1)]);
}
drawarray(myarr);
i++;
}
function stop() {
clearInterval(inter);
}
清空"myarr";在你画画之后。现在的情况是,你画了10个矩形,然后是20个,然后是30个,以此类推