Как сделать несколько движущихся квадратов на холсте? - PullRequest
0 голосов
/ 01 марта 2020

Итак, я сделал движущийся квадрат, который при нажатии кнопки в файле HTML вызывает функцию draw () и dr aws красный квадрат в области холста, который перемещается по холсту. Как сделать так, чтобы одна и та же функция draw () могла создавать несколько движущихся квадратов?

Вот код на данный момент:

var x = 10;
var y = 10;

function draw(){ 
                 var can = document.getElementById("myCanvas");
                 var ctx = can.getContext("2d");    
 var x = 1;

 setInterval(function(){ 
ctx.clearRect(0,0, can.width, can.height);
ctx.fillRect(x, 20, 75, 75);
ctx.fillStyle ="red";
x=x+5;    
 }, 500

 );
  }

Ответы [ 2 ]

0 голосов
/ 02 марта 2020

Извините, не упомянул про кнопку. Так что для btn изменения просты.

  1. Создайте btn div в html,
  2. Добавьте слушателя в этот div. Устанавливать параметры в массивах, если нажата кнопка. Вместо случайной генерации, как это было в моем решении раньше.
  3. Чтение массивов и рендеринг всех прямоугольников из него.

// variables declaration. I suggest to use Arrays for store individual rectangle parameters.

// rectangle start coords x and y
var rcx = [];
var rcy = [];

// delta to move x, y 
var dx = [];
var dy = [];

// rectangle size (if you want it variable)
var size =[];

//counter for created rectangles
var i=0;

// init canvas 
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

// create and collect rectangles parameters on btn push 
// with unique coords, deltas to move, and sizes for each rectangle.

    var btn =document.getElementById('btn');
    btn.addEventListener( 'click', function() {
          
            //count every time you push the btn and create rect
            i=i+1;
            
            //generate rect params x,y, delta x, delta y, size
            rcx[i]=20;
            rcy[i]=20;
            dx[i]=1
            dy[i]=0
            size[i] = 8;
    
   });

// it is optional, but i decide made function for rectangle declaration. It will looks more compact when rendering.

function rect(x, y, size){
    ctx.fillRect(x, y, size, size/1.5);
    ctx.fillStyle = "red";  
}


// finally all together into function draw()


function draw(){ 
    

    
        setInterval(function(){ 
            ctx.clearRect(0,0, canvas.width, canvas.height);

          
            for (var j=1; j<rcx.length; j++) {

                // read arrays
                // render rectangle with params from arrays
                rect(rcx[j],rcy[j],size[j]);
                
                // add delta to move (x,y) and rewrite new coords to arrays
                rcx[j]=rcx[j]+dx[j];
                rcy[j]=rcy[j]+dy[j]};
                
            
        }, 100

        );
         
        
    };

//rendering animation
draw();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            margin: 0 auto;
            padding: 0;
            background-color: rgb(17, 0, 28);
        }
        
        #container{
            position: relative;
            margin-top: 10px;
            margin-left: 50px;
        }
        #canvas {
            z-index: 0;
            position:fixed;
            align-self: center;
            justify-self: center;
            width: 80vw;
            height: 50vw;
            background-color: #ccc; 
        }
        
        #btn {
            margin: 20px 20px 20px 0px;
            padding: 10px;
            position:static; 
            top: 30px;
            font-family: 'Roboto', sans-serif;
            width: 65px;
            background-color: brown;
            cursor: pointer;
            }
        #btn:hover {
            background-color: red;
        }
        
         #btn:active {
            background-color: coral;
        }
        
        
    </style>
</head>
<body>
<div id="container">
  <div id="btn"> Push me </div>
    <canvas id="canvas"></canvas>
</div>
<script src="js1.js"></script>
</body>
</html>
0 голосов
/ 02 марта 2020

Не уверен, что мое решение хорошо, я только начинаю изучать js, но надеюсь, что оно поможет.

// variables declaration. I suggest to use Arrays 
// for store individual rectangle parameters.

// rectangle start coords x and y
var rcx = [];
var rcy = [];

// delta to move x, y 
var dx = [];
var dy = [];

// rectangle size (if you want it variable)
var size =[];

// init canvas 
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

// create and collect rectangles parameters 
// on window load (here 100 rectangles created)
// with unique coords, deltas to move,
// and sizes for each rectangle.
window.onload = function() {
        for (var i=0; i<100; i++) {
            
            // in this solution all parameters randomized, 
            // but you can set whatever you want.
            rcx[i]=(Math.floor(Math.random() * Math.floor(canvas.width)));
            rcy[i]=(Math.floor(Math.random() * Math.floor(canvas.height)));
            dx[i]=  (Math.floor(Math.random() * Math.floor(3))-1);
            dy[i]=(Math.floor(Math.random() * Math.floor(3))-1);
            size[i] = (Math.floor(Math.random() * Math.floor(8)));
}};

// it is optional, but i decide 
// made function for rectangle declaration. 
// It will looks more compact when rendering.

function rect(x, y, size){
    ctx.fillRect(x, y, size, size/2 );
    ctx.fillStyle = "rgba(255,255,255,1)";  
}


// finally all together into function draw()
function draw(){ 
    
        setInterval(function(){ 
            ctx.clearRect(0,0, canvas.width, canvas.height);
            
          
            for (var j=0; j<100; j++) {
                
                // read arrays
                // render rectangle with params from arrays
                rect(rcx[j],rcy[j],size[j]);
                
                // add delta to move (x,y) 
                // and rewrite new coords to arrays
                rcx[j]=rcx[j]+dx[j];
                rcy[j]=rcy[j]+dy[j]};
                
            
        }, 100

        );
        
    };

//rendering animation
draw();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        
        #canvas {
            width: 500px;
            height: 500px;
            background-color: #ccc; 
        }
        
    </style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="js1.js"></script>
</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...