javascript - 错误: Not getting a desired output

标签 javascript html canvas

当字符串包含字符“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>

关于javascript - 错误: Not getting a desired output,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29661555/

相关文章:

html - 将 HTML 表单分为两部分

html - 在 body 中垂直居中两个 div

javascript - navigator.mediaDevices.getUserMedia 与 http 服务器

javascript - 计算 <li> 内 <div> 元素的数量

javascript - 播放 Vimeo 视频时暂停 Bootstrap 轮播

javascript - 如何绘制用三次贝塞尔曲线绘制的椭圆的一部分?

html - 在 HTML5 中屏蔽图像的最佳方式

JavaScript 对象属性在循环中几次正确迭代后随机变为 NaN

javascript - Three.js 中的动态骨骼动画

javascript - 如何将本地存储添加到我的React.js应用程序?