[英]How to change opacity for circles on canvas
所以我在这里要做的是在我的 canvas 上制作多个圆圈,并单独更改每个圆圈的不透明度。 到目前为止,这是我尝试过的,我知道我肯定将间隔放在错误的位置,但我对这些画布的工作原理感到非常困惑:
function makeCircle(x,y)
{
canvas.beginPath();
canvas.arc(x, y, 20, 0, 2 * Math.PI);
color = generateRandomColor();
canvas.fillStyle = color;
canvas.fill();
canvas.lineWidth = 0;
canvas.strokeStyle = color;
setInterval(function()
{
if(canvas.globalAlpha>=.05)
{
canvas.globalAlpha-=.05;
console.log("here");
}
else
{
canvas.globalAlpha = 0;
console.log(canvas.globalAlpha);
clearInterval();
}
}, 2000)
canvas.stroke();
}
据我所知,这样做根本不会改变圆圈的不透明度。
不知道你想用那个嵌套的 setInterval 做什么,或者为什么要使用它......
这是我要做的:
function makeCircle(x, y, color, alpha) { canvas.beginPath(); canvas.globalAlpha = alpha canvas.arc(x, y, 20, 0, 2 * Math.PI); canvas.fillStyle = color; canvas.fill(); } var canvas_doc = document.getElementById("canvas"); var canvas = canvas_doc.getContext("2d"); makeCircle(20, 20, "red", 0.5) makeCircle(30, 30, "blue", 0.5) makeCircle(50, 50, "green", 0.9) makeCircle(120, 20, "red", 1) makeCircle(180, 30, "blue", 1) makeCircle(150, 50, "green", 1)
<canvas id="canvas"></canvas>
很简单,对吧?
我只是在 function 中添加了一些参数来传递颜色和 alpha。
这样我们就可以轻松绘制多个色环。
您想使用 globalAlpha 创建某种 animation ...
我们可以为此使用setInterval
,这是一个示例:
function makeCircle(x, y, color, alpha) { canvas.beginPath(); canvas.globalAlpha = alpha canvas.arc(x, y, 20, 0, 2 * Math.PI); canvas.fillStyle = color; canvas.fill(); } var globalAlpha = 0.1 function draw() { globalAlpha += 0.02 if (globalAlpha > 2) globalAlpha = 0.1 canvas.clearRect(0,0, 999, 999) makeCircle(20, 20, "red", globalAlpha) makeCircle(30, 30, "blue", globalAlpha) makeCircle(50, 50, "green", globalAlpha) makeCircle(120, 20, "red", 1) makeCircle(130, 30, "blue", 1) makeCircle(150, 50, "green", 1) } var canvas_doc = document.getElementById("canvas"); var canvas = canvas_doc.getContext("2d"); setInterval(draw, 50)
<canvas id="canvas"></canvas>
有几件事:
canvas
变量不是 canvas,而是上下文。 重命名它以避免混淆(通常使用ctx
)。clearInterval
接受一个参数:对要清除的间隔的引用。 把它放在一个变量中,然后使用它。ctx.fill()
。 var canvas = document.querySelector('canvas'), ctx = canvas.getContext("2d"); function makeCircle(x, y) { // Save the background var bg = ctx.getImageData(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.arc(x, y, 20, 0, 2 * Math.PI); color = '#f00'; // For the demo ctx.fillStyle = color; ctx.fill(); var timer = setInterval(function() { // Clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // Redraw the background ctx.putImageData(bg, 0, 0); if (ctx.globalAlpha >=.05) { ctx.globalAlpha -=.05; ctx.fill(); } else { ctx.globalAlpha = 0; clearInterval(timer); } }, 50); } ctx.fillRect(50, 50, 30, 100); // For the demo makeCircle(50, 50);
<canvas></canvas>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.