我有一个自定义的图像控件,它像这样呈现

<img id="2344324_Img" />


我正在这样访问HTML 5 canvas对象中的图像:

var imgOne = new Image();
imgOne = document.getElementById('2344324_Img');
imgOne.onload = function() {
  // ..some code

  canvas.drawImage(this, 20, 20);
};


这是正确的方法吗?

最佳答案

如果您的标记中已经包含<img>标记并打算通过getElementById()访问它,则无需调用new Image()

<img id="2344324_Img"/>

<script type='text/javascript'>
// Don't need this...
//var imgOne = new Image();

// Instead just do:
var imgOne = document.getElementById('2344324_Img');
imgOne.onload = function() {
  ..some code
  canvas.drawImage(this, 20, 20);

  // Should be accessible either via `this` or `imgOne`
  //canvas.drawImage(imgOne, 20, 20);
}
</script>

10-07 18:07