javascript 在画布上画一个三角形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32788694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:45:56  来源:igfitidea点击:

drawing a triangle on canvas

javascriptcanvas

提问by samuelk71

I am having trouble drawing a triangle on a canvas. Triangle: equilateral triangle with 2 points on the x-axis. So what I was thinking: I start in the bottom right corner, move up to the next point, and then move to the last point in the lower left. Here is what I have:

我在画布上绘制三角形时遇到问题。三角形:在 x 轴上有 2 个点的等边三角形。所以我在想:我从右下角开始,向上移动到下一个点,然后移动到左下角的最后一个点。这是我所拥有的:

<!doctype html>
    <html lang="en">
    <head>
    <meta charset= "UTF-8">
    
    <script type="text/JavaScript">
     function draw() {
      var canvas = document.getElementById('canvas');
        if (canvas.getContext) {
          var ctx = canvas.getContext('2d');
       
       var sWidth = screen.width;
       var sHeight = screen.height;
          var path=new Path2D();
          path.moveTo((sWidth/2)+50,sHeight/2);
          path.lineTo((sWidth/2),(sHeight/2)-50);
          path.lineTo((sWidth/2)-50,sHeight/2);
          ctx.fill(path);
        }
       }
    
    
    </script>
    </head>
    
    <body onload="draw();">
     <div align = "center">
      <canvas id = "canvas">
    
      </canvas>
    
     </div>
    
    </body>
    </html>

Nothing gets drawn. I read: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes, but I'm not sure what I messed up.

什么都不会画。我读过:https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes,但我不确定我搞砸了什么。

回答by dievardump

You need to give a size to your canvas. Either with CSS, HTML or in JavaScript

您需要为画布指定尺寸。使用 CSS、HTML 或 JavaScript

Here is a snippet that works :

这是一个有效的片段:

 function draw() {
        var canvas = document.getElementById('canvas');
        if (canvas.getContext) {
            var ctx = canvas.getContext('2d');

            var sWidth = canvas.width;
            var sHeight = canvas.height;
            var path=new Path2D();
            path.moveTo((sWidth/2)+50,sHeight/2);
            path.lineTo((sWidth/2),(sHeight/2)-50);
            path.lineTo((sWidth/2)-50,sHeight/2);
            ctx.fill(path);
        }
    }

draw();
<!doctype html>
<html lang="en">
<head>
<meta charset= "UTF-8">

<style>canvas { width: 200px; height: 200px; border: 1px solid red; }</style>
</head>

<body>
  <canvas id="canvas">

  </canvas>
</body>
</html>