首页 > 解决方案 > drawImage() 不工作

问题描述

当我在 chrome 中打开 html 文件时,我只看到背景,我打开控制台,我看到“hi”曾经框架但我看不到我使用 drawImage() “绘制”的图像`

var ctx = document.querySelector('Canvas').getContext('2d')

function draw() {
  ctx.drawImage(document.getElementById('Mario'), 50, 61, 0, 0)
  window.requestAnimationFrame(draw)
  console.log('hi')
}
draw()
#Canvas {
  width: 100%;
  height: 100%;
  background: url(Pictures/Background.jpg);
  margin: -8px;
}
<canvas id='Canvas'></canvas>
<div style='display:none;'>
  <img id='Mario' src='Pictures/Mario.png'>
</div>

标签: javascripthtml5-canvasrequestanimationframe

解决方案


这是你的问题:

ctx.drawImage(document.getElementById('Mario'), 50, 61, 0, 0);

您已将图像宽度和高度设置为0. 改为:

ctx.drawImage(document.getElementById('Mario'), 0, 0, 50, 61);

推荐阅读