[英]Load image from url and draw to HTML5 Canvas
I am having trouble loading an image from a url in javascript.我在从 javascript 中的 url 加载图像时遇到问题。 The code below works, but I don't want to have to have the image loaded from html.
下面的代码有效,但我不想从 html 加载图像。 I want to load the image from a url using pure javascript.
我想使用纯 javascript 从 url 加载图像。
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("imImageId");
ctx.drawImage(img, 0, 0);
Simple, just create an image object in JavaScript, set the src
, and wait for the load event before drawing.很简单,只需在 JavaScript 中创建一个图像对象,设置
src
,然后在绘制之前等待 load 事件。
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>
Easy as this...就这么简单...
var img=new Image();
img.onload=start;
img.src="myImage.png";
function start(){
ctx.drawImage(img,0,0);
}
In case you want a Promise
version instead of the onload
approach:如果你想要一个
Promise
版本而不是onload
方法:
async function drawImage(url, ctx) {
let img = new Image();
await new Promise(r => img.onload=r, img.src=url);
ctx.drawImage(img, 0, 0);
}
let ctx = document.querySelector("#myCanvas").getContext("2d");
await drawImage("https://example.com/image.png", ctx);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.