在画布上画一个三角形

时间:2015-09-25 18:44:17

标签: javascript canvas

我在画布上绘制三角形时遇到问题。三角形:等边三角形,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>
&#13;
&#13;
&#13;

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

1 个答案:

答案 0 :(得分:5)

您需要为画布指定大小。使用CSS,HTML或JavaScript

这是一个有效的代码段:

&#13;
&#13;
 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();
&#13;
<!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>
&#13;
&#13;
&#13;