从动态数组值创建画布条形图

时间:2017-05-17 08:09:53

标签: javascript html canvas

我正在尝试从动态创建的元素数组中创建条形图。

当前数组列表,chrr1 = [xxx,xxx,xxx,xxx,xxx,xxx,xxxx]。我还检查了alert(),将canvas.height设置为200,然后将h循环并除以函数中的10。

然而,条形图尚未创建。我尝试增加高度,但它不起作用。它只显示画布右侧的一个栏(我无法在此处上传图片。上传器似乎无法正常工作。)

var canvas = document.getElementById("ttmrev");
  var c = canvas.getContext("2d");
  c.fillStyle = "#000000";
  var currX = 0;
  var width = 30;
  for(j = 0; j < chrr1.length; j++) {
    var max_value = Math.max.apply(null, chrr1);
    var max_val_str = max_value.toString();
    if (max_val_str.length < 5) {
      canvas.height = "200";
    } else {
      canvas.height = "1000";
    }
    var h = chrr1[j];
    var g = h.toString();
    if (g.length < 5) {
      h = h/10;
    } else if (g.length >= 5) {
      h = h/100;
    } else if (!g || g.length === 0) {
      h = 0;
    }
    c.rect(currX, canvas.height - h, width, h);
    c.fill();
    currX += 40;
    }

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

问题是,您正在调整for循环中的画布大小,这会扭曲画布,使之前的所有绘图都消失。

你应该在for循环之外做画布调整大小的东西,就像这样......

class ViewController: UIViewController {

    @IBOutlet var TextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        TextField.delegate = self
    }

    public func textField(_ textField: UITextField,
                          shouldChangeCharactersIn range: NSRange,
                          replacementString string: String) -> Bool {
        let inverseSet = NSCharacterSet(
            charactersIn:"0123456789.").inverted

        let components = string.components(separatedBy: inverseSet)

        let filtered = components.joined(separator:"")
        return string == filtered
    }
}
var canvas = document.getElementById("ttmrev");
var c = canvas.getContext("2d");
var currX = 0;
var width = 40;
chrr1 = [333, 222, 666, 1200, 444, 1000];

var max_value = Math.max.apply(null, chrr1);
var max_val_str = max_value.toString();
if (max_val_str.length < 5) {
    canvas.height = 200;
} else {
    canvas.height = 1000;
}

for (j = 0; j < chrr1.length; j++) {
    var h = chrr1[j];
    var g = h.toString();
    if (g.length < 5) {
        h = h / 10;
    } else if (g.length >= 5) {
        h = h / 100;
    } else if (!g || g.length === 0) {
        h = 0;
    }
    c.rect(currX, canvas.height - h, width, h);
    c.fillStyle = "#000000";
    c.fill();
    currX += 52;
}
body{margin:10px 0 0 0;overflow:hidden}canvas{border:1px solid #e4e6e8}