canvas.getContext(“2d”)不起作用

时间:2014-12-18 18:55:46

标签: javascript firefox canvas

这是我的代码:

<!DOCTYPE html>
<html>
    <head>
        <link href="style.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript">
            (function drawCanvas(){
                var canv = document.getElementById('testcanvas1');

                if(canv.getContext){
                    alert("test");
                    var context = doof.getContext('2d');

                    context.fillStyle = "rgb(255, 0, 255)";
                    context.fillRect(0, 0, canvas.width, canvas.height);
                }
            })();
        </script>
    </head>
    <body>
        <canvas id="testcanvas1"></canvas>
    </body>
</html>

没有警报,所以我假设变量canv.getContext为false。为什么?一般来说.getContext('2d')对我的firefox不起作用34.我怎样才能使这个funktion工作?

1 个答案:

答案 0 :(得分:0)

您在加载文档之前执行代码。解决方案:

window.onload = function() {
    (function drawCanvas(){
        var canv = document.getElementById('testcanvas1');

        if(canv.getContext){
            alert("test");
            var context = doof.getContext('2d');

            context.fillStyle = "rgb(255, 0, 255)";
            context.fillRect(0, 0, canvas.width, canvas.height);
        }
    })();
}