How to duplicate a triangle randomly inside the canvas?

0

I'm trying to duplicate a triangle randomly inside the canvas when you press any key, type, space bar, or any other. But I do not know how to duplicate if I have to use some kind of constructor/array .

At this moment I only have the canvas and the 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();
    
asked by anonymous 07.03.2018 / 18:22

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))); 
}
    
07.03.2018 / 19:29