[英]Adding integers to array on javascript
I'm developing an application that is supposed to draw some rectangles on a canvas. 我正在开发一个应在画布上绘制一些矩形的应用程序。 The idea is draw them by putting each one at the last's side - I mean, start drawing it where the other finishes. 这个想法是通过将每个人放在最后一面来画它们的-我的意思是,从另一个完成的地方开始画。
I have created a button that takes the values from an input, that was the easy part. 我创建了一个按钮,该按钮从输入中获取值,这很容易。 I add this values to an Array, but each time I push the button, the array is empty again. 我将此值添加到数组中,但是每次按下按钮时,数组再次为空。 I've heard that I need an 'instance variable', but I'm quite lost right now. 我听说我需要一个“实例变量”,但是现在我已经很迷路了。
Any help will be welcome. 任何帮助都将受到欢迎。 this is the code 这是代码
function corta() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var medida1 = document.getElementById('medida2').value;
var medida2 = document.getElementById('medida1').value;
var corte1 = Math.round(medida1);
var corte2 = Math.round(medida2);
var arrayAncho = [];
var arrayLargo = [];
var ancho = 0;
var largo = 0;
arrayLargo.push(medida2);
arrayAncho.push(medida1);
//ancho, largo
document.getElementById('medida2').onclick = function () { this.value = ''; };
document.getElementById('medida1').onclick = function () { this.value = ''; };
//metodo para el ancho
for (var i = 0; i < arrayAncho.length ; i++) {
ancho += arrayAncho[i];
}
if (arrayAncho.length == 1) {
ctx.fillStyle = "#58FA58";
ctx.fillRect(0, largo, corte1, corte2);
} else
if (medida1 > 122 - ancho) {
ctx.fillStyle = "#58FA58";
ctx.fillRect(ancho, largo, corte1, corte2);//ancho, largo
}
medida1 = 0;
medida2 = 0;
}
Every time you run the function you run 每次运行该功能时
var arrayAncho = [];
var arrayLargo = [];
This makes them blank every time. 这使它们每次都是空白。 You have to declare them outside of the function and only reference them inside the code block 您必须在函数外部声明它们,而仅在代码块内部引用它们
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.