Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drawing a triangle on canvas

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.

like image 945
samuelk71 Avatar asked Sep 25 '15 18:09

samuelk71


People also ask

Which tool is used to draw triangle on the canvas?

Choose the Shape tool (U) and select the Triangle tool ( ) from the available options. Position the pointer on the canvas and click and drag to draw a triangle shape on a new shape layer.

How do you draw a triangle?

Draw a straight line. Lay your ruler on the paper, then trace a pencil along the straight edge. This line segment will form one side of your equilateral triangle, which means that you will need to draw two more lines of exactly the same length, each reaching toward a point at a 60° angle from the first line.

What are the different shapes in canvas?

Unlike SVG, <canvas> only supports two primitive shapes: rectangles and paths (lists of points connected by lines).


1 Answers

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>
like image 91
dievardump Avatar answered Oct 05 '22 22:10

dievardump