Canvas放置反弹效果随机图形(实例)

网友投稿 228 2023-04-19


Canvas放置反弹效果随机图形(实例)

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(thhttp://is.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=[cQYDTMaB"#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.http://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;

}

})


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java编程使用Runtime和Process类运行外部程序的方法
下一篇:Java实现从jar包中读取指定文件的方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~