在这段代码我用onload函数,但它仍然不是在画布上显示图像,为什么???

时间:2011-07-23 10:07:43

标签: javascript html5 canvas html5-canvas

<!DOCTYPE HTML>
<html>
<body>

    <canvas id="myCanvas" width="100" height="200" style="border:5px solid #c3c3c3;">
        Your browser does not support the canvas element.
    </canvas>

    <script type="text/javascript">
        var c=document.getElementById("myCanvas");
        var cxt=c.getContext("2d");
        var img=new Image();
        img.onload = function(){
            // execute drawImage statements here};
        cxt.drawImage(img,0, 0, 50, 50, 0, 0);
        }
        img.src = "myimg.png";

    </script>

</body>
</html>

3 个答案:

答案 0 :(得分:1)

也许我错过了什么,但我没有看到任何onload。而且我认为你错过了一些争论。据我所知,drawImage需要3个,5个或9个参数。因为你在7岁,你可能正在寻找九个参数函数。

尝试:

<html>
<head>
<script type="text/javascript">
    function init() {
       var c=document.getElementById("myCanvas");
       var cxt=c.getContext("2d");
       var img=new Image();
       img.onload = function(){
          // execute drawImage statements here;
          // drawImage( src, sx,sy, sw, sh, dx, dy, dw, dh ); <-- 9 arg form.
          // src = the img (new Image();)
          // sx, sy, sw, sh  = The rectangle to draw to.
          // dx, dy = Where to position it.
          // dw, dh = Width and height to scale to.
          cxt.drawImage(img,0, 0, 50, 50, 0, 0, 50, 50);
       }
       img.src = "myimg.png";
    }

    window.onload = init;
</script>
</head>
<body>

<canvas id="myCanvas" width="100" height="200" style="border:5px solid #c3c3c3;">
    Your browser does not support the canvas element.
</canvas>

</body>
</html>

希望有所帮助。要更好地了解如何将canvas与图片一起使用,请尝试访问: http://diveintohtml5.ep.io/canvas.html#images

答案 1 :(得分:0)

我不确定你想要实现什么,但只是在这里显示图像的一些简化代码:

  <script type="text/javascript">
        var c=document.getElementById("myCanvas").getContext("2d");
        var img=new Image();
        img.src = 'myimg.png';
        img.onload = function(){
            // execute drawImage statements here
          c.drawImage(img,0,0);
        }
     </script>

答案 2 :(得分:0)

你的原始代码是正确的,除了drawImage()调用需要两个以上的参数,或者你可以删除除前三个之外的所有参数。

您也不需要挂钩window.onload事件,因为JavaScript正在body元素中执行,具有相同的效果,所以答案指示您在正确的情况下执行此操作,不是必需的。

以下是修复程序的代码:

<!DOCTYPE HTML>
<html>
<body>

    <canvas id="myCanvas" width="100" height="200" style="border:5px solid #c3c3c3;">
        Your browser does not support the canvas element.
    </canvas>

    <script type="text/javascript">
        var c = document.getElementById("myCanvas"),
            cxt = c.getContext("2d"),
            img = new Image();

        img.onload = function(){
            // Execute drawImage() statements here
            cxt.drawImage(img, 0, 0, this.width, this.height, 0, 0, this.width, this.height);
        }
        img.src = "myimg.png";

    </script>

</body>
</html>