canvas html 不工作

canvas html not working

我一直在研究这段代码,我似乎已经正确地创建了这个函数,但是当我 运行 它实际上并没有绘制任何东西?我错过了什么?

我尝试了直线、圆弧、三角形和矩形的不同绘图形式,看是否其中一种不起作用,但它们似乎都不起作用。

谢谢!

 <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>

document.getElementsByName()得到一个元素namedocument.getElementByID应该是document.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

代码中的更改

1) 您需要更改选择选项值的语法

2) 你写错了getElementById()的语法

请检查 Corrected Your Code Jsfiddle

中更正后的示例