HTML5'画布:$(文档).ready(function() - NOT READY

Aze*_*edo 3 jquery html5

我正在尝试使用下面的代码绘制画布.alert()返回undefined.看起来文档已准备好但画布不是.

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/myscript.js"></script>
        <link type="text/css" rel="stylesheet" href="css/normalize.css" media="screen" />

        <title></title>
    </head>
    <body>
        <canvas id="space" width="1500" height="1500"></canvas>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

myscript.js

$(document).ready(function(){
//$(window).load(function() {


    alert($('#space').id); // returns undefined

    dbCanvas = $('#space');
    context = dbCanvas.getContext('2d');
        // IE: {exception} Object doesn't support property or method 'getContext'
        // FF: TypeError: dbCanvas.getContext is not a function

    context.fillStyle = "rgb(200, 0, 0)";
    context.fillRect(10, 10, 55, 50);

});
Run Code Online (Sandbox Code Playgroud)

epa*_*llo 8

嗯jQuery对象中没有id属性.这就是它未定义的原因.

alert($('#space').get(0).id); 
alert($('#space').attr("id")); 
Run Code Online (Sandbox Code Playgroud)

你需要为画布运行DOM

dbCanvas = $('#space').get(0);
context = dbCanvas.getContext('2d');
Run Code Online (Sandbox Code Playgroud)