簡體   English   中英

如何更改畫布上呈現的單個對象的不透明度?

[英]How do I change opacity of individual object rendered on canvas?

我有這些粒子,它們是在畫布上呈現的列表中的對象。 現在他們填充屏幕,如果列表有一百多個條目,那么我刪除前兩個。 我的問題是我想逐漸增加創建的不透明度並在刪除對象之前逐漸減少它。 解決這個問題的最佳方法是什么? 這是我的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>

像這樣的東西?

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM