简体   繁体   English

HTML canvas 不从文件中绘制图像

[英]HTML canvas not drawing image from file

I am trying to load an image from a file and draw it on a canvas. I have this..我正在尝试从文件加载图像并将其绘制在 canvas 上。我有这个..

const canvas  = document.createElement("canvas");
const context = canvas.getContext("2d");

myImage = new Image();
myImage.src = "img/image.jpg";

context.drawImage(myImage, 0, 0, 100, 100);

This is not drawing anything on the screen, where am I going wrong?这不是在屏幕上绘制任何东西,我哪里出错了? I can see the image being loaded by developer tools so I know that it can find the file itself.我可以看到开发人员工具正在加载图像,所以我知道它可以找到文件本身。

If the canvas element is already on the page, you'll need to replace the createElement method with querySelector :如果页面上已存在canvas元素,则需要将createElement方法替换为querySelector

// const canvas  = document.createElement("canvas");
const canvas  = document.querySelector("canvas");
const context = canvas.getContext("2d");

myImage = new Image();
myImage.src = "img/image.jpg";

myImage.addEventListener("load", ()=>{
  context.drawImage(myImage, 0, 0, 100, 100);
}); // Thanks to Xion 14 for the reminder!

Otherwise, you'll need to append the canvas element to the DOM, eg via document.body.appendChild( canvas );否则,您需要将 append canvas 元素添加到 DOM,例如通过document.body.appendChild( canvas );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM