2017-07-29 54 views
0

您可以請在本演示中熟悉並讓我知道爲什麼我無法將圖像加載到HTML畫布中?不能將圖像加載到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>

回答

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); 
 
});
<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>

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); 
 
});
<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>

+0

感謝Ishan,但是新的錯誤是什麼? – Behseini

+0

這是一個與您的image.Lemme問題檢查,但我確定它是所有關於image.Change圖像,它應該工作,而且錯誤將只在日誌中存在,而不是顯示給用戶。 –

+1

它應該是img [0],因爲JQuery沒有選擇DOM元素,它返回一個包含DOM對象的對象 – Ronnie

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元素。