簡體   English   中英

錯誤:未獲得所需的輸出

[英]Error: Not getting a desired output

當字符串包含字符“ e”時,我希望打印一個紅色圓圈,如果包含任何其他字符,則我希望打印一個黑色圓圈。

我不知道我到底在哪里弄錯了。 有人能幫我嗎?。

這是我嘗試的代碼。

HTML

<input id="e-" placeholder="type eg:-e---ee---e" type="text" size="50"/>

<button onclick="start()">diagram</button> 

<canvas id="myCanvas"></canvas>

JavaScript

function start() {
  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  var str = getElementByID("e-");
  var i;
  for( i=0; i < str.length(); i++ ) {
    if( str.charAt(i) == "e" ) {
      ctx.beginPath();
      ctx.arc(100, 75, 10, 0, 2 * Math.PI);
      ctx.fillStyle = "red";
      ctx.fill();
      ctx.stroke();
    } else {
      ctx.beginPath();
      ctx.stroke();
      ctx.arc(100, 75, 10, 0, 2 * Math.PI);

      ctx.fillStyle = "black";
      ctx.fill();
    }
  }
}

您在這里有幾個錯誤。 我將在下面的實時代碼中發表評論:

 function start() { var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d") // must be prefixed with document., small d in Id, and suffixed with value var str = document.getElementById("e-").value; var i = 0, ch; while(ch = str[i++]) { // no () behind length, changed to while loop ctx.beginPath(); if (ch === "e") { // just check straight ctx.arc(100, 75, 10, 0, 2 * Math.PI); ctx.fillStyle = "red"; ctx.fill(); ctx.stroke(); } else { ctx.arc(100, 75, 10, 0, 2 * Math.PI); ctx.fillStyle = "black"; ctx.fill(); } // need to move the arc position on x axis ctx.translate(22, 0); // diameter + 2 pixels } ctx.setTransform(1,0,0,1,0,0); // reset translate } 
 <input id="e-" placeholder="type eg:-e---ee---e" type="text" size="50" /> <button onclick="start()">diagram</button> <canvas id="myCanvas" width=600 ></canvas> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM