How to duplicate a triangle randomly within the canvas?

Asked

Viewed 45 times

0

I’m trying to duplicate a triangle randomly within the canvas when you press some key, like space bar or other. But I don’t know how to duplicate if I have to use some kind of constructor/array.

Until now I only have canvas and triangle:

HTML

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <title>Canvas</title>
   <script src="canvas.js" type="text/javascript" defer></script>
</head>
<body onload="setUp()">
    <h1>Triangle</h1>
    <canvas id="myCanvas" height="500" width="500" style="border: 1px solid black"></canvas>

    <br>
    <button type="button" id="resetbtt" name="button">Reset</button>

</body>

</html>

JS:

let canvas;
let ctx;
let dx = 10;
let dy = 10;
let x = 250;
let y = 250;
let WIDTH, HEIGHT = 500;


function setUp(){
   canvas = document.getElementById("myCanvas");
   ctx = canvas.getContext("2d");
   let resetbtt = document.getElementById('resetbtt');
   drawTriangle();
}

function drawTriangle(){

    ctx.save();
    ctx.translate(x,y)
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(-15, 15);
    ctx.lineTo(15, 15);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();

1 answer

0

let canvas;
let ctx;
let dx = 10;
let dy = 10;
let WIDTH, HEIGHT = 500;


function setUp(){
   canvas = document.getElementById("myCanvas");
   ctx = canvas.getContext("2d");
   let resetbtt = document.getElementById('resetbtt');

   document.body.onkeydown = function(e){
        if(e.keyCode == 32){
            var x = randomInt(0,500);
            var y = randomInt(0,500);
            drawTriangle(x, y);
        }
    }
}

function drawTriangle(x, y) {

    ctx.save();
    ctx.translate(x, y)
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(-15, 15);
    ctx.lineTo(15, 15);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();

}

function randomInt(min, max) { 
    return Math.floor(min + (Math.random() * ((max + 1) - min))); 
}
  • Thomas, it’s not working. The triangle is not randomly reappearing when you press the space bar

  • space bar sometimes creates conflicts

Browser other questions tagged

You are not signed in. Login or sign up in order to post.