尝试在HTML5画布中显示图像

时间:2013-07-20 11:06:02

标签: javascript canvas html5-canvas

我已经尝试了所有在线代码变体。我只想在画布上显示图像。我试过这个网站的代码。

window.onLoad=function(){
  function draw(){  
    var ctx = document.getElementById("canvas1").getContext("2d");  
    var img = new Image();  
    img.src = 'images/ball.png';  
    img.onload = function(){  
        ctx.drawImage(img,0,0);  
    };
  };
};

文件路径不是问题,在没有images文件夹的情况下进行了测试。控制台中没有错误。感谢。

1 个答案:

答案 0 :(得分:1)

在Google中进行一次搜索,然后使用完整的jsfiddle示例:

// Grab the Canvas and Drawing Context
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');

// Create an image element
var img = document.createElement('IMG');

// When the image is loaded, draw it
img.onload = function () {
    ctx.drawImage(img, 0, 0);
}

// Specify the src to load the image
img.src = "http://i.imgur.com/gwlPu.jpg";

http://jsfiddle.net/jimrhoskins/Sv87G/

相关问题