Nel seguente codice, cliccando su avvia, si ha l’urto della pallina rossa su quella gialla.
Cliccando su azzera si riportano le due palline nello loro posizioni iniziali, ma con l’inconveniente che la pallina rossa lascia uno strano cerchietto nella sua ultima posizione, mentre la gialla no.
Vorrei evitare questo strano cerchietto, sapendo perché si forma solo per la pallina rossa e non per quella gialla. Grazie
Lanvoel
codice:
<!doctype html>
<html>
<body>
<canvas id="myCanvas" width="300" height="200" style="border:1px solid red; background:cyan";>
</canvas><br>
velocità <input type="text" id="vel" value=40 size=0> <input type="button" value="OK"> <br><br>
<input type="button" value="avvia1" onclick="avvia()">
<input type="button" value="ferma" onclick="ferma()">
<input type="button" value="azzera" onclick="azzera()">
<script>
var tempo1;
var tempo;
var x=1;
var x1=0;
dx=1;
dx1=1;
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
disegna()
function disegna() {
ctx.strokeStyle="red";
ctx.lineWidth=1;
ctx.moveTo(0,100);
ctx.lineTo(300,100);
ctx.stroke();
ctx.closePath();
ctx.beginPath()
ctx.strokeStyle="blue";
ctx.lineWidth=2;
ctx.fillStyle="yellow"
ctx.arc(100,100,10,0,2*Math.PI);
ctx.fill();
ctx.stroke();
ctx.closePath();
ctx.beginPath()
ctx.strokeStyle="blue";
ctx.lineWidth=2;
ctx.fillStyle="red"
ctx.arc(10,100,10,0,2*Math.PI);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
function avvia() {
velo=vel.value
tempo1=window.setInterval("tempo()",velo);
}
function tempo() {
ctx.clearRect(0,0,myCanvas.width, myCanvas.height);
if(dx==1) {x++;
if(x>=280) {dx=-1}}
if(dx==-1){x--;
if(x<=0) {dx=1}
}
ctx.beginPath()
ctx.strokeStyle="red";
ctx.lineWidth=1;
ctx.moveTo(0,100);
ctx.lineTo(300,100);
ctx.stroke();
ctx.closePath();
ctx.beginPath()
ctx.strokeStyle="blue";
ctx.lineWidth=2;
ctx.fillStyle="yellow"
ctx.arc(100+x1,100,10,0,2*Math.PI);
ctx.fill();
ctx.stroke();
ctx.closePath();
ctx.beginPath()
ctx.strokeStyle="blue";
ctx.lineWidth=2;
ctx.fillStyle="red"
ctx.arc(10+x,100,10,0,2*Math.PI);
ctx.fill();
ctx.stroke();
ctx.closePath();
if(x>=74) {
x=74; y=74;
if(dx1==1) {
x1++;
if(x1>=190) {dx1=-1}
}
if(dx1==-1){
x1--;
if(x1<=-90) {dx1=1}
}
}
}
function ferma() {
clearInterval(tempo1);
}
function azzera(){
clearInterval(tempo1);
x=0; x1=0; dx=1; dx1=1;
ctx.clearRect(0,0,myCanvas.width, myCanvas.height);
disegna();
}
</script>
<br><br>
</body>
</html>