Canvas放置反弹效果随机图形(实例)
程序员文章站
2022-04-29 08:05:31
canvas放置反弹效果随机图形(实例)
var raf;
var arror = [];
var running = false;
//绘制圆...
canvas放置反弹效果随机图形(实例)
var raf; var arror = []; var running = false; //绘制圆形 function createball() { return { x: 0, y: 0, vx: 10-math.random()*10, vy: 10-math.random()*10, radius: 25, color:"red", draw: function() { ctx.beginpath(); ctx.arc(this.x, this.y, this.radius, 0, math.pi * 2, true); ctx.closepath(); ctx.fillstyle = this.color; ctx.fill(); } } } //绘制正方形 function createsquare() { return { x: 0, y: 0, vx: 10-math.random()*10, vy: 10-math.random()*10, color:"red", draw: function() { ctx.beginpath(); ctx.fillstyle = this.color; ctx.fillrect(this.x, this.y,30, 30); ctx.closepath(); } } } //绘制五角星 function createstar() { return { x: 0, y: 0, vx: 10-math.random()*10, vy: 10-math.random()*10, color:"red", draw: function() { ctx.font = "24px serif"; ctx.textbaseline = "hanging"; ctx.fillstyle=this.color; ctx.filltext("五角星",this.x, this.y); } } } //绘制三角形 function createtriangle() { return { x: 0, y: 0, vx: 10-math.random()*10, vy: 10-math.random()*10, color:"red", draw: function() { ctx.beginpath(); ctx.moveto(this.x,this.y); ctx.lineto(this.x+25,this.y+25); ctx.lineto(this.x+25,this.y-25); ctx.fillstyle=this.color; ctx.fill(); } } } //清除 function clear() { ctx.fillstyle = 'rgba(255,255,255,0.3)'; ctx.fillrect(0,0,canvas.width,canvas.height); } //判断图形坐标是否超出画布范围 function draw() { clear(); arror.foreach(function(ball, i){ ball.draw(); ball.x += ball.vx; ball.y += ball.vy; if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) { ball.vy = -ball.vy; } if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) { ball.vx = -ball.vx; } }); raf = window.requestanimationframe(draw); } canvas.addeventlistener('click',function(e){ if (!running) { raf = window.requestanimationframe(draw); running = true; } var colorarr=["#000000","#7f7f7f","#880015","#ed1c24","#ff7f27","#fff200","#22b14c","#00a2e8","#3f48cc","#a349a4","#b97a57","#ffaec9","#b5e61d"]; var graphics = ["round","square","star","triangle"]; var typexz=graphics[math.floor(math.random()*4)]; var ball; switch(typexz){ case "round": ball = createball(); break; case "square": ball = createsquare(); break; case "star": ball = createstar(); break; case "triangle": ball = createtriangle(); break; } ball.x = e.clientx; ball.y = e.clienty; ball.color = colorarr[math.floor(math.random() * 10 + 3)]; arror.push(ball); }); draw(); document.addeventlistener('keydown',function (e) { if(e.keycode==32){ event.preventdefault(); window.cancelanimationframe(raf); running = false; } })
以上这篇canvas放置反弹效果随机图形(实例)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。