canvas上的document.getElementById返回null

时间:2016-09-16 17:17:29

标签: javascript html5 canvas html5-canvas

我是javascript的新手,我正在学习它。在这样做时我遇到了这个问题,我无法弄明白,我在这里是为了你的帮助。

这是我所在的页面,http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_canvas_empty

现在,当我在控制台(firebug)上运行以下命令时,它返回null。

import csv

info = list(csv.reader(open("info.csv", 'rb')))
age = list(csv.reader(open("age.csv", 'rb')))

def copyCSV(age, info, outFileName = 'out.csv'):
    # put age into dict, indexed by ID
    # assumes no duplicate entries

    # 1 - build a dict ageDict to represent data
    ageDict = dict([(entry[0].replace(' ',''), entry[1]) for entry in age[1:] if entry != []])

    # 2 - setup output
    with open(outFileName, 'wb') as outFile:
        outwriter = csv.writer(outFile)
        # 3 - run through info and slot in ages and write to output
        # nb: had to use .replace(' ','') to strip out whitespaces - these may not be in original .csv
        outwriter.writerow(info[0])
        for entry in info[1:]:
            if entry != []:
                key = entry[2].replace(' ','')
                if key in ageDict: # checks that you have data from age.csv
                    entry[5] = ageDict[key]
            outwriter.writerow(entry)

copyCSV(age, info)

为什么我在这里没有得到预期的结果?

1 个答案:

答案 0 :(得分:0)

调用draw-function时已经加载了DOM,这是正确的。

但var canvas = document.getElementById('control'); - 在此之前评估行,因为它不在draw-function中。它在元素渲染之前立即在文档中执行。

我建议您将init函数更改为类似

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');