Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   Объект в Canvas выходит за границы поля (https://javascript.ru/forum/dom-window/84725-obekt-v-canvas-vykhodit-za-granicy-polya.html)

m9kish 29.11.2022 20:51

Объект в Canvas выходит за границы поля
 
Доброго времени суток! Подскажите пожалуйста, как нужно изменить программу, чтоб колобок не выходил за пределы поля?
<!DOCTYPE HTML>
<html>
<body>
<canvas id="myCanvas" width="600" height="400" style="border:3px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script>
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");

function Fon()
{
cxt.clearRect(0, 0, 600, 400);
cxt.fillStyle="blue";
cxt.fillRect(0,0,600,200);
cxt.fillStyle="green";
cxt.fillRect(0,200,600,400);
}
function Kolobok()
{
//колобок
cxt.strokeStyle="red";
cxt.fillStyle="yellow";
cxt.beginPath();
cxt.arc(x1,y1,35,0,Math.PI*2,true);
cxt.closePath();
cxt.stroke();
cxt.fill();
// глазки
cxt.strokeStyle="black";
cxt.fillStyle="black";
cxt.beginPath();
cxt.arc(x2,y2,5,0,Math.PI*2,true);
cxt.closePath();
cxt.stroke();
cxt.fill();
cxt.strokeStyle="black";
cxt.fillStyle="black";
cxt.beginPath();
cxt.arc(x3,y3,5,0,Math.PI*2,true);
cxt.closePath();
cxt.stroke();
cxt.fill();
}
function Vpravo()
{
Fon();
x1=x1+10;
x2=x2+10;
x3=x3+10;
Kolobok();
}

function Vlevo()
{
Fon();
x1=x1-10;
x2=x2-10;
x3=x3-10;
Kolobok();
}

function Vverh()
{
Fon();
y1=y1-10;
y2=y2-10;
y3=y3-10;
Kolobok();
}

function Vniz()
{
Fon();
y1=y1+10;
y2=y2+10;
y3=y3+10;
Kolobok();
}

//Начало игры
//стартовые координаты колобка
x1=50;
y1=200;
y2=200;
y3=200;
x2=40;
x3=60;
Fon();
Kolobok();
</script>

<br>

<button type = "button" onclick="Vpravo();" name = "button1" style = "width: 80px;
height:50px;">
<b> → </b>
</button><br><br>

<button type = "button" onclick="Vlevo();" name = "button2" style = "width: 80px;
height:50px;">
<b> ← </b>
</button><br><br>

<button type = "button" onclick="Vverh();" name = "button3" style = "width: 80px;
height:50px;">
<b> ↑ </b>
</button><br><br>

<button type = "button" onclick="Vniz();" name = "button4" style = "width: 80px;
height:50px;">
<b> ↓ </b>
</button><br><br>
</body>
</html>

Rise 29.11.2022 23:38

m9kish,
x = x + 10 так x = Math.min(x + 10, 600)
x = x - 10 так x = Math.max(x - 10, 0)
y = y + 10 так y = Math.min(y + 10, 400)
y = y - 10 так y = Math.max(y - 10, 0)


Часовой пояс GMT +3, время: 06:14.