버튼을 클릭 할 때마다 캔버스 개체를 이동하는 방법은 무엇입니까?

Maroun

게임을 만들려고하는데 고정 된 행의 그리드에서 무작위로 생성되는 블록이 있습니다 (예 : 행 5 [수평]). 버튼을 클릭 할 때마다 블록이 5 행에서 4 행 (수직)으로 이동하기를 원합니다. 그런 다음 새로운 랜덤 블록이 행 5 등에 생성되기를 원합니다. 어떻게 할 수 있습니까? 지금은 첫 번째 행 (6 행, 7 행 등) 아래에 새 블록 만 생성됩니다.

시각적 참조를위한 스크린 샷

//Accessing canvas
var canvas = document.getElementById('grid');
var ctx = canvas.getContext('2d');

var w = ctx.canvas.width;
var h = ctx.canvas.height;

// Drawing grid
var drawingGrid = function() {

  for (x = 0; x <= w; x += 60) {
    for (y = 0; y <= h; y += 60) {

      // Gray grid
      ctx.globalCompositeOperation = 'destination-over';
      ctx.strokeStyle = "#cccccc";
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(x, 0);
      ctx.lineTo(x, h);
      ctx.moveTo(0, y);
      ctx.lineTo(w, y);

      if (x % 240 === 0) {
        // Black X-axis grid |
        ctx.globalCompositeOperation = "source-over";


        if (x === 0 || x === 480) {
          ctx.lineWidth = 5;
        } else {
          ctx.lineWidth = 1;
        }
        // Middle vertical line
        if (x === 240) {
          // 0-480
          ctx.beginPath();
          ctx.moveTo(x, 0);
          ctx.lineTo(x, 480);
          ctx.strokeStyle = "#222831";
          ctx.stroke();

          // 480-560
          ctx.beginPath();
          ctx.moveTo(x, 480);
          ctx.lineTo(x, 540);
          ctx.strokeStyle = "#cccccc";
          ctx.globalCompositeOperation = 'destination-over';

        } else {
          ctx.beginPath();
          ctx.moveTo(x, 0);
          ctx.lineTo(x, h);
          ctx.strokeStyle = "#222831";
        }



      } else if (y % 240 === 0 || y === 540) {
        // Black Y-axis grid _
        ctx.globalCompositeOperation = "source-over";
        ctx.strokeStyle = "#222831";

        if (y === 0 || y === 540) {
          ctx.lineWidth = 5;
        } else if (y === 480) {
          ctx.lineWidth = 2.5;
        } else {
          ctx.lineWidth = 1;
        }

        ctx.beginPath();
        ctx.moveTo(0, y);
        ctx.lineTo(h, y);

      }
      ctx.stroke();
    }
  }



};

drawingGrid(480, 540, 'grid');

// Starting coordinates
var posX = 0;
var posY = 240;
// Move blocks on Y axis
function moveY(){
  posY +=60;
}
// Spawn random amount of blocks on the field
function gener(){
  posX = 60*Math.floor(8*Math.random());
}

  function spawnRandomObject() {

    // Game Object
      ctx.fillStyle = '#f2a365';
      ctx.globalCompositeOperation = "destination-over";
      ctx.beginPath();
      ctx.fillRect(posX, posY, 60, 60);
      ctx.stroke();
  }

// Blocks moving up
document.getElementById("button").addEventListener("click", function(){
  // Spawn random amount of objects
  for (var i=0; i<Math.floor((Math.random()*8)+1)*2; i++){
    gener();
    spawnRandomObject();

  }
moveY();
});
body{
  background-color: #ececec;
}

canvas{
  padding-left: 0;
    padding-right: 0;
    margin-left: auto;
    margin-right: auto;
    display: block;
}

.row{
  padding: 20px;
  margin: 0;
}
.firstrow{
  width:20%;
}

.mainrow{
  width:60%;
  display: block;
}

.thirdrow{
  width: 20%;
}

.header{
  background-color: #222831;
  color: #ececec;
  padding: 20px;
}

.container{
  margin-top: 20px;
  padding: 0px;
  display: flex;
  box-sizing: inherit;
}
.thirdrow{
  text-align: right;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Shmetris</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <!-- Local CSS -->
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <!-- Header -->
  <div class="header">
    <h1>Shmetris</h1>
  </div>
  <div class="container">

  <!-- Controls -->
    <div class="row first">
        <div class="col">
            <h1>Score: 0</h1>
            <br>
            <button type="button" class="btn btn-dark" id="button">Refresh</button>
        </div>
    </div>

    <!-- Game Area -->
    <div class="row mainrow">
      <div class="col-" id="gamearea">
   
          

        <!-- Canvas -->
        <canvas id="grid" width="480" height="540" style="background: #ececec "></canvas>

      </div>
    </div>

    <!--  -->
    <div class="row thirdrow">
      <div class="col" style="text-align:left;">
        

      </div>
    </div>
  </div>
<!-- Script -->
  <script src="app.js"></script>
  </body>
</html>

마일 레 7

I removed your moveY() function and added the moveRow() function. The game objects (the rects) are saved to a list objects. Their y position is increased on each button click. The old drawn positions are removed, the new positions are drawn. Then the randomly generated blocks are added in the 5th row.

Note that the clearRect() function inside the removeCell() also removes parts of the grid. This causes to redraw the grid every time. You can improve the code by splitting your grid creation in using a sub function which draws the grid on only one cell. Then you can redraw the grid only on those cells that are needed. This probably is a performance boost and makes the code more beautiful in my eyes, but it works like this too.

나는 또한 사용하는 것이 좋습니다 length대신 60예를 들어, 및 길이에 의해 두꺼운 격자 선을 계산 8 * length하는 대신 480등등.

//Accessing canvas
var canvas = document.getElementById('grid');
var ctx = canvas.getContext('2d');

var w = ctx.canvas.width;
var h = ctx.canvas.height;

// Drawing grid
var drawingGrid = function() {

  for (x = 0; x <= w; x += 60) {
    for (y = 0; y <= h; y += 60) {

      // Gray grid
      ctx.globalCompositeOperation = 'destination-over';
      ctx.strokeStyle = "#cccccc";
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(x, 0);
      ctx.lineTo(x, h);
      ctx.moveTo(0, y);
      ctx.lineTo(w, y);

      if (x % 240 === 0) {
        // Black X-axis grid |
        ctx.globalCompositeOperation = "source-over";


        if (x === 0 || x === 480) {
          ctx.lineWidth = 5;
        } else {
          ctx.lineWidth = 1;
        }
        // Middle vertical line
        if (x === 240) {
          // 0-480
          ctx.beginPath();
          ctx.moveTo(x, 0);
          ctx.lineTo(x, 480);
          ctx.strokeStyle = "#222831";
          ctx.stroke();

          // 480-560
          ctx.beginPath();
          ctx.moveTo(x, 480);
          ctx.lineTo(x, 540);
          ctx.strokeStyle = "#cccccc";
          ctx.globalCompositeOperation = 'destination-over';

        } else {
          ctx.beginPath();
          ctx.moveTo(x, 0);
          ctx.lineTo(x, h);
          ctx.strokeStyle = "#222831";
        }



      } else if (y % 240 === 0 || y === 540) {
        // Black Y-axis grid _
        ctx.globalCompositeOperation = "source-over";
        ctx.strokeStyle = "#222831";

        if (y === 0 || y === 540) {
          ctx.lineWidth = 5;
        } else if (y === 480) {
          ctx.lineWidth = 2.5;
        } else {
          ctx.lineWidth = 1;
        }

        ctx.beginPath();
        ctx.moveTo(0, y);
        ctx.lineTo(h, y);

      }
      ctx.stroke();
    }
  }



};

drawingGrid(480, 540, 'grid');

var length = 60;
// Starting coordinates
var posX = 0;
var posY = 4 * length;
var objects = []

function moveRows(){
  for(var i = 0; i < objects.length; i++){
    // remove old objects
    removeCell(objects[i][0], objects[i][1]);
    // move objects
    objects[i][1] += length;
  }
  
  drawingGrid();
  
  for(var i = 0; i < objects.length; i++){
    // redraw objects on new location
    drawCell(objects[i][0], objects[i][1]);
  }
}
// Spawn random amount of blocks on the field
function gener(){
  posX = length*Math.floor(8*Math.random());
}

  function spawnRandomObject() {

    // Game Object
    drawCell(posX, posY);
    objects.push([posX, posY]);
  }

function drawCell(x, y, color){
    ctx.fillStyle = "#f2a365";
    ctx.globalCompositeOperation = "destination-over";
    ctx.beginPath();
    ctx.fillRect(x, y, length, length);
    ctx.stroke();
}

function removeCell(x, y){
    ctx.clearRect(x, y, length, length);
}

// Blocks moving up
document.getElementById("button").addEventListener("click", function(){
  // Spawn random amount of objects
  moveRows();
  for (var i=0; i<Math.floor((Math.random()*8)+1)*2; i++){
    gener();
    spawnRandomObject();

  }
});
body{
  background-color: #ececec;
}

canvas{
  padding-left: 0;
    padding-right: 0;
    margin-left: auto;
    margin-right: auto;
    display: block;
}

.row{
  padding: 20px;
  margin: 0;
}
.firstrow{
  width:20%;
}

.mainrow{
  width:60%;
  display: block;
}

.thirdrow{
  width: 20%;
}

.header{
  background-color: #222831;
  color: #ececec;
  padding: 20px;
}

.container{
  margin-top: 20px;
  padding: 0px;
  display: flex;
  box-sizing: inherit;
}
.thirdrow{
  text-align: right;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Shmetris</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <!-- Local CSS -->
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <!-- Header -->
  <div class="header">
    <h1>Shmetris</h1>
  </div>
  <div class="container">

  <!-- Controls -->
    <div class="row first">
        <div class="col">
            <h1>Score: 0</h1>
            <br>
            <button type="button" class="btn btn-dark" id="button">Refresh</button>
        </div>
    </div>

    <!-- Game Area -->
    <div class="row mainrow">
      <div class="col-" id="gamearea">
   
          

        <!-- Canvas -->
        <canvas id="grid" width="480" height="540" style="background: #ececec "></canvas>

      </div>
    </div>

    <!--  -->
    <div class="row thirdrow">
      <div class="col" style="text-align:left;">
        

      </div>
    </div>
  </div>
<!-- Script -->
  <script src="app.js"></script>
  </body>
</html>

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

버튼을 3 번 클릭 할 때마다 전면 광고를 표시하는 방법은 무엇입니까?

버튼을 클릭 할 때마다 함수를 호출하는 방법은 무엇입니까?

버튼을 클릭 할 때마다 AdMob 전면 광고를 표시하는 방법은 무엇입니까?

버튼을 클릭 할 때마다 새 div를 만드는 방법은 무엇입니까?

버튼을 클릭 할 때 자동 슬라이드를 중지하는 방법은 무엇입니까?

버튼을 클릭 할 때마다 아래로 이동하는 함수를 만드는 방법은 무엇입니까?

클릭할 때마다 tkinter에서 버튼 동작을 재설정하는 방법은 무엇입니까?

다른 버튼을 클릭할 때 다른 이미지를 표시하는 방법은 무엇입니까?

버튼을 클릭 할 때마다 "li"요소를 현재 위치에서 n 번째 위치로 이동하는 방법은 무엇입니까?

클릭할 때마다 다른 버튼 세트를 표시하는 버튼을 만드는 방법은 무엇입니까?

버튼을 클릭 할 때 텍스트를 레이블로 설정하는 방법은 무엇입니까?

버튼을 클릭 할 때 스톱워치 타이머를 추가하는 방법은 무엇입니까?

iOS 앱 개발에서 버튼을 클릭 할 때 다른보기를 여는 방법은 무엇입니까?

jquery에서 버튼을 클릭 할 때마다 입력 값을 추가하는 방법은 무엇입니까?

버튼을 클릭할 때마다 블록을 회전하는 방법은 무엇입니까?

동일한 버튼을 클릭 할 때마다 다른 코드를 실행하는 방법은 무엇입니까?

버튼을 클릭 할 때 버튼의 ID를 얻는 방법은 무엇입니까?

Flutter에서 버튼을 클릭 할 때 객체를 배열에 저장하는 방법은 무엇입니까?

10 초마다 div를 자동으로 새로 고침하고 버튼을 클릭 할 때 중지하는 방법은 무엇입니까?

버튼을 클릭 할 때 ModalPopupExtender를 숨기는 방법을 설정하는 방법은 무엇입니까?

js를 사용하여 버튼을 클릭할 때 테이블을 숨기는 방법은 무엇입니까?

버튼을 다시 클릭 할 때 여기서 핸들러를 중지하는 방법은 무엇입니까?

버튼을 여러 번 클릭 할 때 다른 JS 함수를 호출하는 방법은 무엇입니까?

버튼을 클릭 할 때마다 텍스트 필드를 하나씩 만드는 방법은 무엇입니까?

버튼을 클릭 할 때 이미지를 변경하는 방법은 무엇입니까?

Android TV 액션 버튼을 클릭 할 때 detailsFragment 데이터를 변경하는 방법은 무엇입니까?

버튼을 클릭할 때 div를 페이드 인하는 방법은 무엇입니까?

Firebase는 버튼을 클릭 할 때마다 새 개체를 만듭니다.

swt에서 버튼을 클릭 할 때 텍스트 상자를 만드는 방법은 무엇입니까?

TOP 리스트

뜨겁다태그

보관