如何更改在画布上渲染的单个对象的不透明度?

问题描述 投票:0回答:1

我有这些粒子,它们是在画布上呈现的列表中的对象。现在,它们会填充屏幕,如果列表中有一百多个条目,那么我将删除前两个条目。我的问题是我想逐渐增加创建时的不透明度,并在删除对象之前逐渐降低它。最好的方法是什么?这是我的js:

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var dots = new Array();

function createDot(xStart, yStart, radius, movementX, movementY){
    this.xStart = (typeof xStart !== 'undefined') ? xStart : Math.floor(Math.random() * c.width);
    this.yStart = (typeof yStart !== 'undefined') ? yStart : Math.floor(Math.random() * c.height);
    this.movementX = (typeof movementX !== 'undefined') ? movementX : Math.floor(Math.random() * 50-25)/50;
    this.movementY = (typeof movementY !== 'undefined') ? movementY : Math.floor(Math.random() * 50-25)/50;
    this.radius = (typeof radius !== 'undefined') ? radius : Math.floor(Math.random() * 20);
    ctx.beginPath();
    ctx.arc(xStart,yStart,radius, 0,2*Math.PI, false);
    ctx.fillStyle = 'white';
    ctx.strokeStyle = 'white';
    ctx.fill();
    ctx.stroke();
}
function animate(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    dots.push(new createDot());
    for(i=0;i<dots.length;i++){
        let d = dots[i];
        
        ctx.beginPath();
        ctx.arc(d.xStart+=d.movementX, d.yStart+=d.movementY,d.radius, 0,2*Math.PI, false);
        ctx.fillStyle = 'white';
        ctx.fill();
        ctx.strokeStyle = 'white';
        ctx.stroke();  
    }

    if(dots.length>100){
        dots.splice(0,2);
    }
    
    requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
canvas {
  background: black
}
<canvas id=canvas></canvas>
javascript web canvas html5-canvas particles
1个回答
0
投票

这样的事情?

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var dots = new Array();

function createDot(xStart, yStart, radius, movementX, movementY){
    this.xStart = Math.floor(Math.random() * c.width);
    this.yStart = Math.floor(Math.random() * c.height);
    this.movementX = Math.floor(Math.random() * 50-25)/50;
    this.movementY = Math.floor(Math.random() * 50-25)/50;
    this.radius =  Math.floor(Math.random() * 20);
    this.opacity = 0
}

function animate(t){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    dots.push(new createDot());
    for(i=0;i<dots.length;i++){
        let d = dots[i];
        ctx.beginPath();
        ctx.arc(d.xStart+=d.movementX, d.yStart+=d.movementY,d.radius, 0,2*Math.PI,0);
        let a = dots.length>99 && i<20 ? 1-(20-i)*0.05 : Math.min(1, d.opacity+=0.05);
        ctx.fillStyle = `rgba(255,255,255,${a})`;
        ctx.fill();
    }
 
    if(dots.length>100){
        dots.splice(0,2);
    }
    
    requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
canvas {
  background:black
}
<canvas id=canvas ></canvas>
© www.soinside.com 2019 - 2024. All rights reserved.