같은 높이의 캔버스에 여러 파이프를 표시하려고하는데 for 루프를 사용한 후에도 많은 파이프가 아닌 단일 파이프가 표시됩니다.
<script>
var tryCanvas = document.getElementById("myCanvas");
var c = tryCanvas.getContext("2d");
var myCall = [];
function Squares() {
for(var i =0; i < 10; i++){
this.x = Math.random()* tryCanvas.clientWidth;
this.y = 0;
this.w = 20;
this.h = 60;
this.counter = 0;
this.draw = function() {
c.beginPath();
c.rect(this.x, this.y, this.w, this.h)
c.fill();
}
}
this.update = function() {
if(this.x < 0){
this.x = 0;
}
this.x -= 1;
this.draw();
}
}
var holder = new Squares;
setInterval(callFun, 10);
function callFun() {
c.clearRect(0,0,tryCanvas.clientWidth, tryCanvas.clientHeight);
holder.update();
}
</script>
생성자 함수를 배열로 푸시하면 캔버스에 아무것도 표시되지 않고 콘솔에서 undefined 또는 NaN이 제공됩니다. 그러나 "this"없이 수행하면 rects 수가 생성됩니다. 내가 여기서 뭘 잘못하고 있니?
화면을 따라 막대를 이동하도록 업데이트되었습니다.
이 작업 예제를 참조하십시오 : https://codepen.io/bkfarns/pen/braWQB?editors=1010
This.draw는 for 루프의 마지막 반복 값으로 만 생성됩니다.
또한 사이드 노드로서 일반적으로 new Squares
생성자를 호출하는 대신 new Squares()
. 생성자를 호출하면 메서드가 호출됩니다.
그러나 아래 코드가 문제를 해결한다고 생각합니다. 시도해보십시오.
<body>
<canvas id="myCanvas"/>
</body>
<script>
var tryCanvas = document.getElementById("myCanvas");
var c = tryCanvas.getContext("2d");
var myCall = [];
function Squares() {
this.draw = function(xOffset) {
for(var i =0; i < 10; i++){
this.x = (i * xOffset) + (5*i)//Math.random()* tryCanvas.clientWidth;
this.y = 0;
this.w = 20;
this.h = 60;
c.beginPath();
c.rect(this.x, this.y, this.w, this.h)
c.fill();
}
}
}
var holder = new Squares();
var xOffset = 20;
setInterval(function() {
c.clearRect(0,0,tryCanvas.clientWidth, tryCanvas.clientHeight);
holder.draw(xOffset)
xOffset--;
}, 1000)
</script>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다