我有一些不同的形状(我只包括三角形的代码,因为它们都是相同的)是在用户旋转鼠标滚轮时生成的,但我无法弄清楚如何使它们消失时间,以便屏幕不会快速完全填满。这是代码:
<html>
<head>
<script>
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;
}
function handleClick(x,y) {
var colors = ['red','yellow','blue','purple','green'];
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);
context.fillStyle = triangle.triangleColor;
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
t.x += t.vx;
t.y += t.vy;
}
}
function fillBackgroundColor() {
context.fillStyle = "black";
context.fillRect(0,0,canvas.width,canvas.height);
}
window.onload = init;
</script>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
</body>
</html>
答案 0 :(得分:1)
我将时间添加为三角形对象的属性:
function Triangle(x,y,triangleColor) {
...
this.time = 100;
}
并根据时间的不透明度来确定:
function drawTriangle(triangle) {
...
var c = triangle.triangleColor
context.fillStyle = 'rgba(' + c[0] + ', ' + c[1] + ', ' + c[2] + ', ' + (triangle.time / 100) + ')';
一旦时间用完,三角形将从列表中删除:
function resizeCanvas() {
...
if(t.time === 0) {
triangles.splice(i,1);
}
}
另外,为了更容易使用rgba值绘制形状,我将颜色变量从字符串数组转换为rgb值数组的数组:
var colors = [[255,0,0],[255,255,0],[0,0,255],[128,0,128],[0,255,0]];
这是一个实现的jsfiddle: