现在我有用户旋转鼠标滚轮时创建的形状,它们会在一定时间后逐渐消失。我如何在每个跟随它的形状后面生成一条线索并慢慢消失?这是代码:
var canvas;
var context;
var triangles = [];
var timer;
function init() {
canvas = document.getElementById('canvas');
context = canvas.getContext("2d");
resizeCanvas();
window.addEventListener('resize', resizeCanvas, false);
window.addEventListener('orientationchange', resizeCanvas, false);
canvas.onwheel = function(event) {
handleClick(event.clientX, event.clientY);
};
var timer = setInterval(resizeCanvas, 30);
}
function Triangle(x, y, triangleColor) {
this.x = x;
this.y = y;
this.triangleColor = triangleColor;
this.vx = Math.random() * 30 - 15;
this.vy = Math.random() * 30 - 15;
this.time = 100;
}
function handleClick(x, y) {
var colors = [
[0, 170, 255],
[230, 180, 125],
[50, 205, 130]
];
var triangleColor = colors[Math.floor(Math.random() * colors.length)];
triangles.push(new Triangle(x, y, triangleColor));
for (var i = 0; i < triangles.length; i++) {
drawTriangle(triangles[i]);
}
}
function drawTriangle(triangle) {
context.beginPath();
context.moveTo(triangle.x, triangle.y);
context.lineTo(triangle.x + 25, triangle.y + 25);
context.lineTo(triangle.x + 25, triangle.y - 25);
var c = triangle.triangleColor
context.fillStyle = 'rgba(' + c[0] + ', ' + c[1] + ', ' + c[2] + ', ' + (triangle.time / 100) + ')';
context.fill();
}
function resizeCanvas() {
canvas.width = window.innerWidth - 20;
canvas.height = window.innerHeight - 20;
fillBackgroundColor();
for (var i = 0; i < triangles.length; i++) {
var t = triangles[i];
drawTriangle(t);
if (t.x + t.vx > canvas.width || t.x + t.vx < 0)
t.vx = -t.vx
if (t.y + t.vy > canvas.height || t.y + t.vy < 0)
t.vy = -t.vy
if (t.time === 0) {
triangles.splice(i, 1);
}
t.time -= 1;
t.x += t.vx;
t.y += t.vy;
}
}
function fillBackgroundColor() {
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
}
init()
&#13;
<canvas id="canvas" width="500" height="500"></canvas>
&#13;
答案 0 :(得分:0)
在构造函数中为三角形对象属性添加一个空数组和不透明度属性,分别调用它们,例如trails
和alpha
。
定义轨迹中所需的最大鬼三角数。我发现3是一个很好的价值:
var MAX_GHOSTS = 3;
使三角形绘制函数将alpha通道值作为其第二个参数,并从函数本身中删除不透明度计算:
function drawTriangle(triangle, alpha) { // two parameters required }
当前在计时器回调中(在循环内)绘制三角形,计算并更新调用drawTriangle
时使用的三角形的alpha值。将选定三角形属性的副本推送到三角形的轨迹数组:复制冻结x,y位置。不推动每个计时器调用将鬼影进一步分开:
if( t.time%2 == 0) {
t.trails.push(
{ x: t.x, y: t.y, alpha: t.alpha, triangleColor: t.triangleColor}
);
}
同样在定时器回调中,在现有的绘图循环之前,添加一个新的双嵌套循环结构
外部循环检索三角形数组中每个条目的trail数组。如果trail数组长度超过MAX_GHOST,则删除其第一个元素(使用splice
)。
内部循环使用说j
作为索引,从trail数组中获取下一个元素,例如调用它crumb
。计算一个alpha值,使其快速淡出并绘制它:
drawTriangle( crumb, (j+1)/(MAX_GHOSTS + 2) * crumb.alpha);
希望你喜欢!