简体   繁体   English

如何修复 HTML5 canvas globalAlpha 问题?

[英]How do fix HTML5 canvas globalAlpha problem?

I'm currently trying to create a particle system for HTML5 canvas for a game, and I needed to make the particles fade out over time.我目前正在尝试为游戏的 HTML5 画布创建粒子系统,我需要让粒子随着时间的推移逐渐消失。 I didn't want to have to be limited to rgba(), so I tried to use ctx.globalAlpha = alpha.我不想受限于 rgba(),所以我尝试使用 ctx.globalAlpha = alpha。 The code to make it fade works, but I can not erase the last circles, they just fade out too, and it creates a line.使其淡出的代码有效,但我无法擦除最后一个圆圈,它们也淡出,并创建了一条线。

Here is the JS code:这是JS代码:

class Particle{
   //Non important declarations
    display(ctx){
        this.a = this.a < 0 ? 0 : this.a;
        ctx.globalAlpha = 1;
        ctx.globalAlpha = this.a;

        ctx.fillStyle=this.color;
        ctx.arc(this.x, this.y, this.rad, 0, Math.PI*2, false);
        ctx.fill();


    }

}

let P=new Particle(200, 200, 20, 180, 270, 5, 0.01, "blue");
const can= document.getElementById("canvas");
const c= can.getContext("2d");
can.height=innerHeight;
can.width=innerWidth;
clear=function(col){
    c.globalAlpha=1;
    c.fillStyle=col;
    c.fillRect(0,0,innerWidth,innerHeight);
}
window.setInterval(function (){
    clear("white");
    P.update();
    P.display(c);

Where did I mess up or need to add something?我在哪里搞砸了或需要添加一些东西?

You need to wrap the code that draw the particle inside .save() and .restore()您需要将绘制粒子的代码包裹在 .save() 和 .restore() 中

ctx.save();
this.a = this.a < 0 ? 0 : this.a;
ctx.globalAlpha = this.a;

ctx.fillStyle=this.color;
ctx.arc(this.x, this.y, this.rad, 0, Math.PI*2, false);
ctx.fill();
ctx.restore();

This way the changes made to global properties (globalAlpha, fillStyle...) will not affect other particles.这样,对全局属性(globalAlpha、fillStyle...)所做的更改不会影响其他粒子。

Update更新

I had not understood the problem.我没有理解这个问题。 you are drawing one particle but because you do not call .beginPath() the calls to .arc() accumulate, and on every update all the previous arcs are redrawn您正在绘制一个粒子,但是因为您没有调用 .beginPath(),所以对 .arc() 的调用会累积,并且在每次更新时都会重新绘制所有先前的弧

You must call .beginPath() before drawing each circle:您必须在绘制每个圆之前调用 .beginPath() :

display(ctx){
    ctx.save();
    this.a = this.a < 0 ? 0 : this.a;
    ctx.globalAlpha = this.a;
    ctx.fillStyle=this.color;
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.rad, 0, Math.PI*2, false);
    ctx.fill();
    ctx.restore();
}

Note: you still need to use .save()/.restore() if you plan on adding more particles注意:如果您打算添加更多粒子,您仍然需要使用 .save()/.restore()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM