为什么这个JavaScript在我的<canvas>标签中不是一个矩形?</canvas>

时间:2011-05-05 02:30:29

标签: javascript html html5 canvas

为什么这不起作用?

<html> 
        <head> 
                <title>Learning the basics of canvas</title> 
                <meta charset="utf-8"> 
                <script type="text/javascript" src="http://ajax.googleapis.com?/ajax/libs/jquery/1/jquery.min.js"></script> 
                <script type="text/javascript">
                        $(document).ready(function() {
                        var canvas = $("#myCanvas"); 
                        var context = canvas.get(0).getContext("2d");
                        context.fillRect(40, 40, 100, 100); 
                        });
                </script> 
        </head> 
        <body> 
                <canvas id="myCanvas" width="500" height="500"> 
                        <!-- Insert fallback content here --> 
                </canvas> 
        </body> 
</html>

4 个答案:

答案 0 :(得分:5)

您的代码缺少doctype,并且存在拼写错误。

文档类型:

<!DOCTYPE html>

错字:

http://ajax.googleapis.com?/ajax/libs/jquery/1/jquery.min.js

应该是

http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js

固定代码:

<!DOCTYPE html>
<html> 
        <head> 
                <title>Learning the basics of canvas</title> 
                <meta charset="utf-8"> 
                <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> 
                <script>
                        //<![CDATA[
                        $(document).ready(function() {
                        var canvas = $("#myCanvas"); 
                        var context = canvas.get(0).getContext("2d");
                        context.fillRect(40, 40, 100, 100); 
                        });
                        //]]>
                </script> 
        </head> 
        <body> 
                <canvas id="myCanvas" width="500" height="500"> 
                        <!-- Insert fallback content here --> 
                </canvas> 
        </body> 
</html>

答案 1 :(得分:3)

您需要DOCTYPE。在页面顶部插入<!DOCTYPE html>

答案 2 :(得分:0)

添加HTML 5 doctype标记。许多浏览器默认情况下仍然会渲染XHTML,您需要指出这是HTML 5格式。

http://www.w3schools.com/html5/tag_doctype.asp

答案 3 :(得分:-1)

尝试canvas.getContext('2d'),不介入get(0)