开发者

Why isn’t this JavaScript drawing a rectangle in my <canvas> tag?

Why won’t this work?

<html> 
        <head> 
                <title>Learning the basics of canvas</title> 
                <meta charset="utf-8"> 
                <script type="text/javascr开发者_如何学Pythonipt" 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>


Your code is missing a doctype, and there's a typo.

Doctype:

<!DOCTYPE html>

Typo:

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

should be

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

Fixed code:

<!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>


You need a DOCTYPE. Insert <!DOCTYPE html> at the very top of your page


Add the HTML 5 doctype tag. Many browsers are also still rendering XHTML by default and need you'll need to indicate that this is a HTML 5 format.

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


Try canvas.getContext('2d'), without the intervening get(0).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜