1

我对 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>
4

2 回答 2

2

好吧,而不是canvas.drawImage(img, 0, 0);应该调用它context- context.drawImage(img, 0, 0);。希望能帮助到你 :)

于 2012-09-14T04:25:47.417 回答
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/

于 2012-09-14T04:20:53.857 回答