HTML5 canvas 的画线无法使用 javascript

Drawing line to HTML5 canvas not working using javascript

我正在使用以下代码画一条线到 html canvas。但不幸的是,我在 canvas 中没有看到任何一行。我什至没有发现任何错误。

    <!DOCTYPE html>
<html>
    <head>
        <title>TODO supply a title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>
<body>
    <br> <br> <br>
        <input id="start" type="button" value="Start" onclick="startstop()" />
        <input type="button" value="Turn Left" />
        <input type="button" value="Turn Right" />
         <br> <br>

        <canvas id="Canvas" style="width:800px; height: 600px; border: 1px solid black;"> </canvas>

         <script>

             function startstop(){
                 var elem = document.getElementById("start");
                if (elem.value==="Start")
                {
                    elem.value = "Stop";
                    var mycanvas=document.getElementById("Canvas");
                   // alert(mycanvas);
                    var ctx=mycanvas.getContext('2d');
                    ctx.beginPath();
                    ctx.moveTo(10,400);
                    ctx.lineTo(200,400); 
                    ctx.lineWidth=10;
                    ctx.strokeStyle="#ff0000";
                    ctx.stroke();     
                }
                   else
                       elem.value = "Start";
             }
         </script>
</body>

这是代码的 jsfiddle http://jsfiddle.net/8ebLLwa9/ 谁也能帮我找出错误吗?

您的 canvas height/width 应该是 canvas 本身的属性,而不是样式属性:

<canvas id='Canvas' width="800px" height="600px" style="border: 1px solid black;"></canvas>

此外,对于您的 jsfiddle,将加载状态从 "onLoad" 更改为 "No wrap - in head"

使用宽度和高度属性而不是 css 样式定义您的 canvas:

<canvas id='Canvas' width='800' height='600' style="border: 1px solid black;"> </canvas>