矩形不動 (Rectangle is not moving)


問題描述

矩形不動 (Rectangle is not moving)

我正在嘗試編寫一個移動的矩形,但它不起作用,我不明白為什麼。我為矩形創建了一個類並給了參數值。然後我畫了一個矩形。我正在嘗試將 5 的值添加到矩形的 x 但沒有發生任何事情。

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

var width = 50;

class Rectangle{
  constructor(x, y){
    this.x = x;
    this.y = y;
  }

  draw(){
    ctx.beginPath();
    ctx.rect(this.x, this.y, width, height);
    ctx.fillStyle = "0095DD";
    ctx.fill();
    ctx.closePath();
  }
}

function movingRectangle(){
  var rect = new Rectangle(canvas.width/2 ‑ width/2, 300);
  rect.draw();
  rect.x += 5;
}

function draw(){
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  movingRectangle();
}

var interval = setInterval(draw, 10);

參考解法

方法 1:

You're recreating rect on each movingRectangle() call, effectively resetting its position to the initial value.

Move this:

var rect = new Rectangle(canvas.width/2 ‑ width/2, 300);

Out of the movingRectangle() function ‑ you only need to create the Rectangle instance once.

方法 2:

I managed to do a short example, based in your code, and leaving the Rectangle constructor outside:

function movingRectangle(){
    let x = rect ? rect.x + 5 : canvas.width/2 ‑ width/2;
  if (!rect)
    rect = new Rectangle(x, 300);
  rect.x = x;
  rect.draw();
}

https://jsfiddle.net/nicoavn/vc254q0a/4/

(by user12788973shkapernicoavn)

參考文件

  1. Rectangle is not moving (CC BY‑SA 2.5/3.0/4.0)

#draw #javascript






相關問題

使用Java繪製維恩圖 (Draw Venn diagram using Java)

android中的ontouch:獲取X和Y坐標並在該點上繪製圓 (ontouch in android: getting X and Y coordinates and drawing circle on that point)

如何在android上將谷歌地圖圖層作為片段佈局移動 (how to move google map layers as fragment layout on android)

onTouch() 無法繪製畫布 (onTouch() can't draw canvas)

佈局僅在屏幕關閉或離開應用程序並返回後顯示兒童 (Layout only shows children after screen turn off or leaving the app and coming back)

將形狀對象的 ArrayList 繪製到框架 (Paint ArrayList of Shape Objects to Frame)

多線程圖形 (multithreading Graphics)

一次性繪製所有 DrawableGameComponents (Drawing all DrawableGameComponents in a single batch)

html5畫布繪製帶有額外數據的圓形變量 (html5 canvas draw circle variables with extra data)

iphone初學者問題:畫一個矩形。我究竟做錯了什麼? (Beginner iphone question: drawing a rectangle. What am I doing wrong?)

連接 4 Android Studio 繪製空格 (Connect 4 Android Studio Draw empty spaces)

矩形不動 (Rectangle is not moving)







留言討論