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

3 回答 3

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

于 2011-07-26T15:16:12.450 回答
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>
于 2012-11-27T18:14:50.007 回答
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>
于 2011-07-23T10:36:14.527 回答