无法将图像加载到HTML

无法将图像加载到HTML

您能否看一下这个演示,让我知道为什么我无法将图像加载到HTML canvas中?
我收到此错误:

{
  "message": "Uncaught TypeError: c.getContext is not a function",
  "filename": "https://stacksnippets.net/js",
  "lineno": 24,
  "colno": 17
}

$(document).ready(function() {
  var expose = function() {
    var c = $("#myCanvas");
    var ctx = c.getContext("2d");
    var img = $("#scream");
    ctx.drawImage(img, 10, 10);
  };
  setTimeout(expose, 2000);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Image to use:</p>
<img id="scream" width="220" height="277" src="https://www.w3schools.com/tags/img_the_scream.jpg" alt="The Scream">

<p>Canvas:</p>
<canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;">
  Your browser does not support the HTML5 canvas tag.
</canvas>

最佳答案

好吧,因为JQuery返回了一个包含DOM元素的对象,并且使用#myCanvas实际上并没有选择DOM元素



$(document).ready(function() {
  var expose = function() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("scream");
    ctx.drawImage(img, 10, 10);
  };
  setTimeout(expose, 2000);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Image to use:</p>
<img id="scream" width="220" height="277" src="https://www.w3schools.com/tags/img_the_scream.jpg" alt="The Scream">

<p>Canvas:</p>
<canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;">
  Your browser does not support the HTML5 canvas tag.
</canvas>

07-24 16:23