从url加载图像并绘制到HTML5 Canvas

时间:2015-04-11 00:14:29

标签: javascript html5 image canvas html5-canvas

我无法在javascript中从网址加载图片。下面的代码有效,但我不想让从html加载图像。我想使用纯javascript从网址加载图片。

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("imImageId");
ctx.drawImage(img, 0, 0);

3 个答案:

答案 0 :(得分:21)

简单,只需在JavaScript中创建一个图像对象,设置src,然后在绘制前等待加载事件。

工作示例:



var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image();
img.onload = function() {
    ctx.drawImage(img, 0, 0);
};
img.src = 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png';

<canvas id="myCanvas"></canvas>
&#13;
&#13;
&#13;

答案 1 :(得分:6)

这很容易......

var img=new Image();
img.onload=start;
img.src="myImage.png";
function start(){
    ctx.drawImage(img,0,0);
}

答案 2 :(得分:0)

如果您希望使用var a="[item1,item2,item3,itemN]" var splitted = a.split(","); splitted[0] = splitted[0].replace("[",""); splitted[splitted.length-1] = splitted[splitted.length-1].replace("]",""); console.log(splitted);版本而不是Promise方法:

onload