2015-10-07 114 views
0

我一直在處理這段代碼,我似乎創建了正確的函數,但是當我運行它時,它實際上並沒有繪製任何東西?我錯過了什麼?canvas html不工作

我嘗試了不同的線條,弧形,三角形和矩形的繪圖形式,看看它們中的一個是不是工作,但他們都沒有工作。

謝謝!

<html> 
 
    <head> 
 
     <title>Hwk8 Drawable</title> 
 
     <meta charset="UTF-8"> 
 
     <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
 
     <script type="text/javascript"> 
 
      function draw() 
 
      { 
 
       shapeSelected = document.index.shapeChosen.value; 
 
       //creating canvas object 
 
       canvas = document.getElementByID("myCanvas"); 
 
       ctx = canvas.getContext("2d"); 
 
       ctx.fillStyle = "rgb(0,255,0)"; 
 
       
 
       if (shapeSelected == "line") 
 
       { 
 
        ctx.moveTo(0,0); 
 
        ctx.lineTo(200,100); 
 
        ctx.stroke(); 
 
       } 
 
       else if (shapeSelected.equals("arc")) 
 
       { 
 
        ctx.beginPath(); 
 
        ctx.arc(95,50,40,0,2); 
 
        ctx.stroke(); 
 
       } 
 
       else if (shapeSelected === "triangle") 
 
       { 
 
        ctx.beginPath(); 
 
        ctx.moveTo(75,0); 
 
        ctx.lineTo(150,100); 
 
        ctx.lineTo(0,100); 
 
        ctx.lineTo(75,0); 
 
        ctx.closePath(); 
 
        ctx.stroke(); 
 
       } 
 
       else if (shapeSelected.equals("rectangle")) 
 
       { 
 
        ctx.strokeRect(50,50,50,50); 
 
        ctx.fillRect(25,25,100,100); 
 
       } 
 
      } 
 
     </script> 
 
    </head> 
 
    <body> 
 
     <form action ="index.jsp"> 
 
      <h2>Choose what you want to draw</h2> 
 
      <select name="shapeChosen" required onChange="draw()"> 
 
       <option value="" selected disabled>Select a Shape</option> 
 
       <option value="line">Line</option> 
 
       <option value="arc">Arc</option> 
 
       <option value="triangle">Triangle</option> 
 
       <option value="square">Square</option> 
 
      </select> 
 
     </form> 
 
     <canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;"> 
 
     Your browser does not support the HTML5 canvas tag.</canvas> 
 
     
 
    </body> 
 
</html>

+0

Wha你的控制檯是否顯示?...使用調試器並檢查draw()函數是否被調用? – AkshayJ

回答

0

使用document.getElementsByName()通過name得到一個元素,document.getElementByIDdocument.getElementById。並使用==(或===),而不是.equals()

function draw() 
{ 
    shapeSelected = document.getElementsByName("shapeChosen")[0].value; 
    //creating canvas object 
    canvas = document.getElementById("myCanvas"); 
    ... 
} 

而且你的最後一條語句必須(shapeSelected =="square")而不是(shapeSelected == "rectangle")作爲<option>它的定義爲:<option value="square">Square</option>

Fiddle Example