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

San*_*jay 0 html javascript 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>
Run Code Online (Sandbox Code Playgroud)

kev*_*nji 5

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

文档类型:

<!DOCTYPE html>
Run Code Online (Sandbox Code Playgroud)

错字:

http://ajax.googleapis.com?/ajax/libs/jquery/1/jquery.min.js
Run Code Online (Sandbox Code Playgroud)

应该

http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
Run Code Online (Sandbox Code Playgroud)

固定代码:

<!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>
Run Code Online (Sandbox Code Playgroud)