javascript的绘图与画布错误

时间:2014-01-02 02:43:39

标签: javascript html5 canvas

我无法在此代码中找到错误。该代码用于根据用户的输入绘制带有画布的图形。它引发了我2个错误:

未捕获TypeError:undefined不是函数canvas.html?option = circulo:14

未捕获的TypeError:无法调用null的“getContext”方法

var my_canvas = document.getElementById("a");
var con = my_canvas.getContext("2d");

var check = function(){
    if((document.getElementById('opcion').value) === 'circulo'){
        con.beginPath();
        con.arc(75, 75, 20, 0, 2*Math.PI);
        con.closePath();
    }else if((document.getElementById('opcion').value) === 'rectangulo'){
        con.strokeRect(100,100,20,50);

    }else if((document.getElementById('opcion').value) === 'arcos'){
       con.beginPath();
       con.arc(75,75,35,0,Math.PI);
       con.stroke();
    }else{
        alert("Ha ingresado un valor invalido");
    }
};

1 个答案:

答案 0 :(得分:2)

您的document.getElementById(“a”)无效。你的画布的id真的是“a”吗?你的HTML看起来像这样:

<canvas id="a" width="200" height="100"></canvas> 

如果你有一个id为“a”(id,而不是类)的画布,那么你的代码可能需要在window.onload函数中,因为它在你的文档加载之前就已经运行了。