drawImage()不适用于canvas

时间:2014-10-01 20:44:31

标签: javascript html image canvas

这是我的代码,我无法弄清楚我做错了什么。当我预览它时,图像不在那里,只有画布边框。

<!DOCTYPE html>

<html>
<head>
  <meta charset="UTF-8">  
    <title>Page Title</title>
</head>

<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>

<body>

<script>

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var sticky = new Image();
sticky.src = "sticky.png";
sticky.onload = function() {
context.drawImage(sticky, 0, 0);
};

</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

控制台显示指向您文件的链接。看看是否正确

在绘制图像之前,您可能需要等到图像加载完毕。试试这个:

&#13;
&#13;
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    make_base();
    function make_base()
    {
      base_image = new Image();
      base_image.src = 'http://techtastico.com/files/2014/06/Apple-Swift-Logo.png';
      base_image.onload = function(){
        context.drawImage(base_image, 0, 0);
      };
    }
&#13;
    <canvas id="myCanvas" width="200" height="100"
    style="border:1px solid #000000;">
    </canvas>
&#13;
&#13;
&#13;