Javascript 从 url 加载图像并绘制到 HTML5 Canvas
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29572560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load image from url and draw to HTML5 Canvas
提问by HymanHallam
I am having trouble loading an image from a url in javascript. The code below works, but I don't want to have to have the image loaded from html. I want to load the image from a url using pure javascript.
我在从 javascript 中的 url 加载图像时遇到问题。下面的代码有效,但我不想从 html 加载图像。我想使用纯 javascript 从 url 加载图像。
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("imImageId");
ctx.drawImage(img, 0, 0);
回答by Alexander O'Mara
Simple, just create an image object in JavaScript, set the src, and wait for the load event before drawing.
很简单,只需在 JavaScript 中创建一个图像对象,设置src,然后在绘制之前等待加载事件。
Working Example:
工作示例:
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>
回答by markE
Easy as this...
就这么简单...
var img=new Image();
img.onload=start;
img.src="myImage.png";
function start(){
ctx.drawImage(img,0,0);
}

