drawing a triangle on canvas

允我心安 提交于 2020-01-21 11:35:09

问题


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:

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


回答1:


You need to give a size to your canvas. Either with CSS, HTML or in 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>


来源:https://stackoverflow.com/questions/32788694/drawing-a-triangle-on-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!