试着写了如下的代码,但是这样就会让圆形疯狂出现,位置好像也没有在移动的样子
应该怎么改比较好呢?
隐约觉得是不是可以用合集达成呀
<body>
<canvas width="640" height="480" id="b"></canvas>
<br><button id="a">画圆</button>
<script>
let c={r:40};
let id=null;
const cv=document.querySelector("canvas");
const gc=cv.getContext("2d");
const a=document.querySelector("#a");
a.addEventListener("click",()=>{
draw();
})
function draw(){
c.x+=1;
c.y+=1;
id=setInterval(draw,10);
gc.beginPath();
gc.lineWidth=5;
gc.strokeStyle="blue";
gc.arc(x=parseInt(Math.random()*640),y=parseInt(Math.random()*480),c.r,0,2*Math.PI);
gc.stroke();
}
</script>
</body>
运用canvas画布实现的话,需要在圆移动过程中不断的清空画布,所以要整体添加一个定时器,定期清空画布,清空后再把每个圆新的位置画出来,达到移动的效果,实现如下:
<body>
<canvas width="640" height="480" id="b"></canvas>
<br><button id="a">画圆</button>
<script>
let c = { r: 10,x:10,y:10 };
let id = null;
const cv = document.querySelector("canvas");
const gc = cv.getContext("2d");
const a = document.querySelector("#a");
let circleArr = [];
a.addEventListener("click", () => {
// draw(10,10);
console.log(circleArr);
circleArr.push({
x:Math.random()*640,
y:Math.random()*480,
})
})
id = setInterval(() => {
gc.clearRect(0,0,640,480);
let newArr = [];
for(var i = 0;i < circleArr.length;i++){
if(circleArr[i].x < 640){
circleArr[i].x += 1;
circleArr[i].y += 1;
newArr.push(circleArr[i]);
draw(circleArr[i].x, circleArr[i].y);
}
}
circleArr = newArr;
}, 10);
function draw(x, y) {
x += 1;
y += 1;
gc.beginPath();
gc.lineWidth = 5;
gc.strokeStyle = "blue";
gc.arc(x, y, c.r, 0, 2 * Math.PI);
gc.stroke();
}
</script>
</body>
需要给每个对象添加定时器,id=setInterval(draw,10);只会无限添加㘣修改gc.arc(x,y)才能动