canvas动画越来越卡顿解决

更新时间: 2023-04-14 10:54:07

今天在写canvas动画的时候,发现网页开着会越来越卡顿,一开始我以为是 requestAnimationFrame 的问题,但我后来发现不是,那么就只可能是动画循环的问题了。

最后再动画循环代码里找了半天,发现是ctx.clip()导致的卡顿,于是修改代码如下,ctx.clip()必须要配合ctx.save(),ctx.restore()使用:


 






 








































 



const draw = () => {
    ctx.save()
    let ringwidth = ring.value.offsetWidth
    let ringheight = ring.value.offsetHeight
    ctx.clearRect(0, 0, ringwidth, ringheight);
    //clip在动画循环里必须配合ctx.save ctx.restore使用,不然内存会爆
    ctx.beginPath();
    ctx.arc(width/2, height/2, r, 0, Math.PI * 2)
    ctx.clip();

    if(parseFloat(props.percent) > 0) {
        ctx.beginPath();
        ctx.lineWidth = 1;
        ctx.fillStyle = waveColor2
        ctx.globalAlpha= 1;

        Q2 += speed2;
        if (Q2 >= 2 * Math.PI) {
            Q2 = 0
        }
        for (let x = width / 2 - r; x <= width / 2 + r; x++) {
            let y = A2 * Math.sin(x * W2 + Q2) + H2;
            ctx.lineTo(x, y);
        }
        ctx.lineTo(width / 2 + r, height / 2 + r);
        ctx.lineTo(width / 2 - r, height / 2 + r);
        ctx.closePath()
        ctx.fill()

        ctx.beginPath();
        ctx.fillStyle = lingrad;
        ctx.globalAlpha= 1;
        ctx.lineWidth = 1;
        ctx.moveTo(0, height / 2);

        Q += speed;
        if (Q >= 2 * Math.PI) {
            Q = 0
        }

        for (let x = width / 2 - r; x <= width / 2 + r; x++) {
            let y = A * Math.sin(W * x + Q) + H;
            ctx.lineTo(x, y);
        }
        ctx.lineTo(width / 2 + r, height / 2 + r);
        ctx.lineTo(width / 2 - r, height / 2 + r);
        ctx.fill();

        ctx.closePath();
        ctx.restore()
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

现在不卡顿了,问题解决了~