我想在两点之间画一条线,看起来像是一条动画的移动线,经过一段时间后会从终点逐渐消失。
我可以画一个移动,但不能使其消失。我该怎么做?我是Canvas的新手。
var canvas = document.getElementById('paper');
var c = canvas.getContext("2d");
var startX = 50;
var startY = 50;
var endX = 1000;
var endY = 1000;
var amount = 0;
setInterval(function() {
amount += 0.005; // change to alter duration
if (amount > 1) amount = 1;
c.clearRect(0, 0, canvas.width, canvas.height);
c.strokeStyle = "black";
c.moveTo(startX, startY);
// lerp : a + (b - a) * f
c.lineTo(startX + (endX - startX) * amount, startY + (endY - startY) * amount);
c.stroke();
}, 30);
https://jsfiddle.net/ashokd23/aucd8hgy/2/
最佳答案
一种简单的方法是更改线条的不透明度,类似于更改颜色的方式。您可以像在css中一样使用rgba(红色,绿色,蓝色,alpha)颜色空间,只是更改alpha值。
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors
例:
var canvas = document.getElementById('paper');
var c = canvas.getContext("2d");
var startX = 50;
var startY = 50;
var endX = 1000;
var endY = 1000;
var amount = 0;
var opacity = 0;
setInterval(function() {
amount += 0.005; // change to alter duration
opacity += 0.005;
if (amount > 1) amount = 1;
c.clearRect(0, 0, canvas.width, canvas.height);
c.strokeStyle = `rgba(0,0,0, ${opacity}`;
c.moveTo(startX, startY);
// lerp : a + (b - a) * f
c.lineTo(startX + (endX - startX) * amount, startY + (endY - startY) * amount);
c.stroke();
}, 30);
<canvas id="paper" width="500" height="500"></canvas>