你能不能参加这个演示,让我知道为什么我无法将图像加载到HTML画布中?
我收到此错误:
{
"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>
&#13;
答案 0 :(得分:2)
因为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);
});
&#13;
<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>
&#13;
答案 1 :(得分:2)
您需要进行两项更改:
var ctx = c[0].getContext("2d");
var img = document.getElementById('scream');
第一个: jQuery equivalent of getting the context of a Canvas
对于第二种,预计你要传递CSSImageValue或HTMLImageElement或SVGImageElement或HTMLVideoElement或HTMLCanvasElement或ImageBitmap或OffscreenCanvas,jQuery返回一个jQuery对象而不是DOM元素。
答案 2 :(得分:0)
应该是这样的
$(document).ready(function() {
var expose = function() {
var c = $("#myCanvas");
var ctx = c[0].getContext("2d");
var img = $("#scream");
ctx.drawImage(img, 10, 10);
};
setTimeout(expose, 2000);
});
&#13;
<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>
&#13;