0

我无法使用类的功能绘制图像。我已经尝试过 this.img 和 var img 但它们都不起作用。我添加了 jquery-libary 的在线资源以将其置于在线状态,但在我的电脑上,我使用的是一个正在工作的离线资源!

<!doctype html>


<head>

    <link rel="stylesheet" href="js\jquery-ui-1.10.1.custom.css"/>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js">      </script>



<script type="text/javascript">

    var canvas;
    var ctx;
    var BurgerArray = new Array(50);

    function burger()
    {
        this.x = 10;
        this.y = 20;
        this.img = new Image();
        img.src='Img/Burger1.png'; 
        img.onload = function()
        {

        }
        this.teken = function()
        {
            ctx.drawImage(img,20,20);

        }

    }




    var b;
    $(document).ready(function() 
    {
        canvas =document.getElementById("MyCanvas");
        ctx =canvas.getContext("2d");

        b = new burger();
        b.teken();

    });

</script>
<style type="text/css">
#MyCanvas
{
    margin:auto; 
    display:block; 
    border:dashed; 
    border-color:#0F0;
}
</style>  
</head>


<body style=" width:100%; height:100%;">

<canvas id="MyCanvas" width="1000" height="600"></canvas>

</body>


</html>
4

1 回答 1

0

当您创建一个新对象时,它的范围与全局范围不同。将实现更改为:

function burger(canvas)
{
    this.x = 10;
    this.y = 20;
    this.canvas = canvas;
    this.ctx = canvas.getContext('2d');
    this.teken = function() {
        this.ctx.drawImage(img,20,20);
    };
}

$(document).ready(function() {
    var canvas = document.getElementById("MyCanvas");
    var b = new burger(canvas);
    b.teken();
});
于 2013-04-16T17:51:24.580 回答