为什么context.drawImage()不能在html画布中工作?

时间:2014-10-03 20:31:58

标签: javascript html5 canvas drawimage

我试图把图像文件" sticky.png"进入一个帆布盒,但我得到的只是一个空白的画布。任何人都可以指出我做错了什么和/或给我代码有效吗?

<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.onload = function() {
context.drawImage(sticky, 0, 0);
sticky.src = "sticky.png";
};


</script>

</body>

2 个答案:

答案 0 :(得分:2)

您需要在sticky.src之前加入sticky.onload

<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
<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>

Fiddle

答案 1 :(得分:0)

有时作为 workAround ,我们必须在画布之前加载图像。这很不寻常,但是 WORKS 。然后,您只需隐藏图像。不要忘记使用setTimeOut等到图像加载完毕!

setTimeout("paintStar()", 2000);

function paintStar() {
    var canva3 = document.getElementById('canvas3');
    canva3.width = 640;
    canva3.height = 480;
    var ct3 = canva3.getContext('2d');
    var img = new Image();
    img.src = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ3DlDGTyfaFMtUf9GYykLglqfS8GzHbeKRV5vDfHraV1ihNIYo';

    ct3.drawImage(img, 0, 0);
    ct3.drawImage(img, 0, 0, 20, 20, 10, 200, 20, 20);
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>CANVAS</title>
    <style>
        .canvas-1 {
            width: 640px;
            height: 480px;
            border: 1px solid #777;
            
        }
        .img-1 {
            display: none;
        }

    </style>
    <script src="canva3.js" defer></script>
</head>

<body>
<div class="img-1"><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ3DlDGTyfaFMtUf9GYykLglqfS8GzHbeKRV5vDfHraV1ihNIYo" alt=""></div>
<canvas id="canvas3" style="border: 2px solid #444;">Doesn't work!</canvas>

</body>

</html>