window.onload = function() {//页面加载完成才执行的代码//}上面的不行,是因为这2个对象没有初始化,就调用方法,报错,可以这样写window.onload = function() { canvas = document.getElementById("myCanvas"); context = canvas.getContext("2d");context.rect(20,20,150,100);context.stroke();}