下面是代码部分
<style>
body{
display: flex;
justify-content: center;
}
</style>
</head>
<body>
<canvas id = "canvas" width="400" height="300"></canvas>
</body>
<script>
let boxx = 20;
let boxy = 30;
//盒子的左上角的位置
let boxwidth = 350;
let boxheight= 250;
//盒子的大小
let ballrad = 10;
//将要绘制球的半径
let boxboundx = boxwidth + boxx-ballrad;
//右边界
let boxboundy = boxheight + boxy -ballrad;
//下边界
let inboxboundx = boxx + ballrad;
//左边界
let inboxboundy = boxy + ballrad;
//上边界
let ballx = 50;
let bally = 50;
//球的初始位置
let ctx;
//保存画笔
let grad;
//保存梯度
let ballvx = 1;
let ballvy = 2;
//初始的速度
let color;
//保存颜色值
let arr= [
[255,0,0],
[255,255,0],
[0,255,0],
[0,255,255],
[0,0,255],
[255,0,255]
];
//初始球的移动速度
function init(){
let i;
ctx = document.querySelector("canvas").getContext("2d");
grad = ctx.createLinearGradient(boxx,boxy,boxx+boxwidth,boxy+boxheight);
for(let i=0;i<arr.length;i++){
color = `rgb(${arr[i][0]},${arr[i][1]},${arr[i][2]})`;
grad.addColorStop(i*1/7,color);
};
ctx.fillStyle = grad;
//给小球填充样式
// ctx.strokeStyle = grad;
ctx.lineWidth =ballrad;
//设置线宽
moveball();
setInterval(moveball,50);
};
function moveball(){
ctx.clearRect(boxx,boxy,boxwidth,boxheight);
//清除画布,不写会得到像贪吃蛇一样的东西
moveandcheck();
//调用moveandcheck在绘制之前先进行判断
ctx.fillRect(boxx,boxy,ballrad,boxheight);
//绘制左墙
ctx.fillRect(boxx,boxy,boxwidth,ballrad);
//绘制上墙
ctx.fillRect(boxx+boxwidth-ballrad,boxy,ballrad,boxheight);
//绘制右墙
ctx.fillRect(boxx,boxy+boxheight-ballrad,boxwidth,ballrad);
//绘制下墙
ctx.beginPath();
ctx.arc(ballx,bally,ballrad,0,2*Math.PI,true);
ctx.fill();
// ctx.strokeRect(boxx,boxy,boxwidth,boxheight);
};
function moveandcheck(){
let nballx = ballx+ballvx;
let nbally = bally + ballvy;
//移动的位置
if(nballx>boxboundx){
ballvx=-ballvx;
nballx = boxboundx;
};
//是否超出右边界
if(nballx<inboxboundx){
nballx = inboxboundx;
ballvx = -ballvx;
};
//是否超出左边界
if(nbally>boxboundy){
ballvy = -ballvy;
nbally = boxboundy;
};
//是否超出下边界
if(nbally<inboxboundy){
ballvy = -ballvy;
nbally = inboxboundy;
};
//是否超出上边界
ballx = nballx;
bally = nbally;
};
init();
//调用
</script>
这里面用到的各种API试试基本就都会了,想要做出好效果还是得多做案例,除非你有个好头脑,反正我是笨的不行了