画布drawImage不起作用,但fillrect做

时间:2012-09-14 04:10:08

标签: javascript html5 canvas

我是javascript的新手,但不是编程...对于我的生活,我无法弄清楚这一点。我想在画布上画一个图像。我可以画一个矩形而不是图像。

这是我的代码:

<head>
    <meta http-equiv = "Content-type" content = "text/html;charset=utf-8">
    <meta name = "viewport" id = "viewport" content = "width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;"/>
    <script type = "text/javascript">
        function drawPic()
        {
            ////////////// DOESN'T WORK /////////////////// 
            var canvas = document.getElementById('mainCanvas');
            if (canvas.getContext)
            {
                var context = canvas.getContext('2d');
                var img = new Image();
                img.onload = function ()
                {
                    canvas.drawImage(img, 0, 0);
                };
                img.src = "pic1.jpg";
            }


            ///////////////////////////////////////////////////////////////
            ///////////// WORKS //////////////////////////////////////////
            if (canvas.getContext)
            {
                var context = canvas.getContext('2d');
                context.fillStyle = "rgb(150,29,28)";
                context.fillRect(2, 2, 96, 96);
            }
        }
    </script>
</head>
<body onload = "drawPic();">
    <canvas id = "mainCanvas"></canvas>
</body>

2 个答案:

答案 0 :(得分:2)

而不是canvas.drawImage(img, 0, 0);应该在context - context.drawImage(img, 0, 0);上调用它。希望它有所帮助:)

答案 1 :(得分:0)

您需要进行AJAX通话。

在代码中添加类似的内容,图片应加载:

window.onload = function() {
        // make ajax call to get image data url
        var request = new XMLHttpRequest();
        request.open("GET", "http://www.html5canvastutorials.com/demos/assets/dataURL.txt", true);
        request.onreadystatechange = function() {
          // Makes sure the document is ready to parse.
          if(request.readyState == 4) {
            // Makes sure it's found the file.
            if(request.status == 200) {
              loadCanvas(request.responseText);
            }
          }
        };
        request.send(null);
      };

有关完整示例,请参阅本教程:http://www.html5canvastutorials.com/advanced/html5-canvas-load-image-data-url/