}
}
}
//绘制三角形
function createTriangle() {
return {
x: 0,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,0.3)';
ctx.fillRect(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放置反弹效果随机图形(实例)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程之家。
原文链接:https://www.f2er.com/js/37074.html