[英]Error: Not getting a desired output
I am looking to print a red circle when the string contains a character 'e' and a black circle if it contains any other character. 当字符串包含字符“ e”时,我希望打印一个红色圆圈,如果包含任何其他字符,则我希望打印一个黑色圆圈。
I do not know where exactly I am getting it wrong. 我不知道我到底在哪里弄错了。 Can someone help me?.
有人能帮我吗?。
This is the code I tried. 这是我尝试的代码。
HTML HTML
<input id="e-" placeholder="type eg:-e---ee---e" type="text" size="50"/>
<button onclick="start()">diagram</button>
<canvas id="myCanvas"></canvas>
The JavaScript 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();
}
}
}
You have several errors here. 您在这里有几个错误。 I'll comment in the live code below:
我将在下面的实时代码中发表评论:
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.