vendredi 26 mars 2021

How can I generate a random rectangle in a canvas without touching the lines?

How can I make the rectangle in the canvas appear randomly anywhere in the canvas but it will never touch the division lines? the rectangle should always be the one I wrote in the code

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
//
ctx.rect(20, 20, 40, 25);
//

ctx.moveTo(100, 0);
ctx.lineTo(100, 500);
ctx.moveTo(200, 0);
ctx.lineTo(200, 500);
ctx.moveTo(0, 75);
ctx.lineTo(300, 75);
ctx.stroke();

</script> 

</body>
</html>



Aucun commentaire:

Enregistrer un commentaire