简体   繁体   English

如何在画布中绘制图像

[英]How to draw an image in a canvas

So I was trying to draw an img in a canvas I tried everything but in the console it says img is not a property or something like that I don't remember so can anyone help?所以我试图在画布上绘制一个img我尝试了一切,但在控制台中它说img is not a property或类似的东西,我不记得了,所以有人可以帮忙吗? Here's the js这是js

function setupcanvas() {
  var canvas = document.querySelector('canvas')
  var c = canvas.getContext("2d")
  c.beginPath();
  var img = new image()
  img.src = "flappy_bird_bird.png"
  img.onload = function(){
    c.drawImage(img, 100, 100)
  }
}

Edit Thx to mhkanfer "sorry if the name is wrong" I fixed it将 Thx 编辑为 mhkanfer“对不起,如果名称错误”我修复了它

You were mostly right, though their are a couple of things:你大部分是对的,尽管他们是几件事:

  1. Make sure Image() is capitalized确保Image()大写
  2. Make sure your image src file actually exists in that directory确保您的图像 src 文件确实存在于该目录中
  3. And make sure your canvas has a width and height, if you haven't specified that anywhere, you canvas wont be shown并确保你的画布有宽度和高度,如果你没有在任何地方指定,你的画布不会被显示

If you were to revise this, it would look something like:如果你要修改它,它看起来像:

function setupcanvas() {

  var canvas = document.querySelector('canvas')
  var c = canvas.getContext("2d")

  canvas.width = canvas.height = 200;

  var img = new Image()
  img.src = "example.png"

  img.onload = function(){
    c.drawImage(img, 0, 0)
  }

}

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

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