[英]How to make multiple elements in a canvas
I'm trying to show multiple pipes in the canvas of same height but even after using a for loop it is showing a single pipe and not a lot of it 我试图在相同高度的画布上显示多个管道,但是即使使用了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>
If I push the constructor function in an array it's not showing anything in the canvas and in the console it's giving undefined or NaN. 如果我将构造函数推入数组中,则它在画布上不显示任何内容,而在控制台中,它给出的是undefined或NaN。 But if I do it without "this" its generating the number of rects. 但是,如果我不使用“ this”就这样做会产生rects的数量。 What am I doing wrong here? 我在这里做错了什么?
Updated to move the bars along the screen 更新后可沿屏幕移动条形图
See this working example: https://codepen.io/bkfarns/pen/braWQB?editors=1010 请参阅此工作示例: https : //codepen.io/bkfarns/pen/braWQB?editors=1010
This.draw will only get created with the values from the last iteration of the for loop. 仅使用for循环的最后一次迭代中的值创建this.draw。
Also as a side node, usually instead of new Squares
you call the constructor like new Squares()
. 同样作为一个侧节点,通常代替new Squares
调用构造函数,例如new Squares()
。 When you call the constructor you are calling a method. 当您调用构造函数时,您正在调用一个方法。
But I think the code below fixes your issues. 但是我认为以下代码可以解决您的问题。 Try it out: 试试看:
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.