2016-05-12 110 views
4

這不斷收到一個錯誤消息,說它不是一個函數,請幫助!document.getElementById()。getContext('2d')不是一個函數

var ctx = document.getElementById('canvas').getContext('2d'); 

HTML:

<html> 
<head> 
    <title>Canvas Race</title> 
    <script src="jquery-2.2.3.js"></script> 
    <style type="text/css"> 
     canvas { 
      border: 1px solid black; 
      background-image: url("http://www.gamefromscratch.com/image.axd?picture=road2048v2.png"); 
      background-size: 200px 300px; 
      background-position-y: -81px; 
     } 
     </style> 
</head> 
<body> 

    <div id="canvas"> 
     <canvas id="myCanvas" width="1100" height="150" ></canvas> 
    </div> 
    <div id="winner"></div> 

</body> 
</html> 

的Javascript:

<script type="text/javascript"> 
    var blueCar = new Image(); 
    var redCar = new Image(); 

    // images 
    function image(){ 
     blueCar.src = "http://worldartsme.com/images/car-top-view-clipart-1.jpg"; 
     redCar.src = "http://images.clipartpanda.com/car-clipart-top-view-free-vector-red-racing-car-top-view_099252_Red_racing_car_top_view.png"; 
     window.requestAnimationFrame(draw); 
    } 
    function draw() { 
     var ctx = document.getElementById('canvas').getContext('2d'); 
     ctx.globalCompositeOperation = 'destination-over'; 

     //blue car 
     ctx.drawImage(blueCar, 10, 10, 100, 100); 
    } 
    image(); 

</script> 

我已經搜查各地,但我還沒有找到任何工作我不要;「知道,如果它有用我的jquery做任何事情。

+0

你有一個canvas元素的id =「canvas」嗎? – ray

+0

是的,我是否已將它全部設置好了 – Angel

+1

在運行此代碼時是否加載了您的文檔? (如果您的腳本位於文檔的頭部,並且它不作爲就緒處理程序的一部分運行,則您的畫布元素尚不存在。) – ray

回答

5

你引用了一個div使用該ID那裏...... 的DIV沒有屬性方法,例如.getContext(),所以這裏是工作的一部分:

var blueCar = new Image(); 
 
    var redCar = new Image(); 
 

 
    // images 
 
    function image(){ 
 
     blueCar.src = "http://worldartsme.com/images/car-top-view-clipart-1.jpg"; 
 
     redCar.src = "http://images.clipartpanda.com/car-clipart-top-view-free-vector-red-racing-car-top-view_099252_Red_racing_car_top_view.png"; 
 
     window.requestAnimationFrame(draw); 
 
    } 
 
    function draw() { 
 
     var ctx = document.getElementById('canvas').getContext('2d'); 
 
     ctx.globalCompositeOperation = 'destination-over'; 
 

 
     //blue car 
 
     ctx.drawImage(blueCar, 10, 10, 100, 100); 
 
    } 
 
    image();
<html> 
 
<head> 
 
    <title>Canvas Race</title> 
 
    <script src="jquery-2.2.3.js"></script> 
 
    <style type="text/css"> 
 
     canvas { 
 
      border: 1px solid black; 
 
      background-image: url("http://www.gamefromscratch.com/image.axd?picture=road2048v2.png"); 
 
      background-size: 200px 300px; 
 
      background-position-y: -81px; 
 
     } 
 
     </style> 
 
</head> 
 
<body> 
 

 
    <div id="mycanvas"> 
 
     <canvas id="canvas" width="1100" height="150" ></canvas> 
 
    </div> 
 
    <div id="winner"></div> 
 

 
</body> 
 
</html>

+2

謝謝我沒有注意到ID的 – Angel

相關問題