我想在点之间画一条线,而它看起来像一段动画移动线,一段时间后从终点渐渐消失。
我可以画一个动人但不能让它淡出。我该怎么做?我是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);
答案 0 :(得分:1)
一种非常简单的方法是改变线的不透明度,类似于改变量的方式。您可以像使用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>