Draw a triangle in HTML canvas based on three given lenths

前端 未结 2 1071
野的像风
野的像风 2021-01-24 15:06

I\'m trying to create a function that draws a triangle in the middle of an HTML canvas based on three given lengths, I thought this would be an easy intro to HTML canvas, I was

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-24 15:24

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.font = "20px Times New Roman";
    ctx.fillStyle = "black";
    ctx.textAlign = "center";
    ctx.strokeStyle = "black";
    var canvasSize = [parseInt(c.width), parseInt(c.height)];
    var _side_1 = 5, _side_2 = 3, _side_3 = 4; //All values are taken assuming as centimeter unit.
    var factor = 37.7952755906;
    var sides = [_side_1, _side_2, _side_3];
    sides.sort(function(a, b){return a-b});
    var halfPerimeter = (_side_1 + _side_2 + _side_3) / 2;
    var area = Math.sqrt(halfPerimeter * (halfPerimeter - _side_1) * (halfPerimeter - _side_2) * (halfPerimeter - _side_3));
    var height = ((2 * area) / sides[2]).toPrecision(5);
    var slopeOfBase = Math.sqrt(Math.pow(sides[0], 2) - Math.pow(height, 2));
    			
    ctx.beginPath();
    ctx.setLineDash([]);
    ctx.moveTo((canvasSize[0]/2 - 0.5 * sides[2] * factor), (canvasSize[1]/2 + 0.5 * height * factor));
    ctx.lineTo((canvasSize[0]/2 + 0.5 * sides[2] * factor), (canvasSize[1]/2 + 0.5 * height * factor));
    ctx.fillText("c = " + sides[2] + " cm",(canvasSize[0]/2 - 0.5 * sides[2] * factor + canvasSize[0]/2 + 0.5 * sides[2] * factor) / 2,(canvasSize[1]/2 + 0.5 * height * factor + canvasSize[1]/2 + 0.5 * height * factor) / 2 + 15);
    ctx.lineTo((canvasSize[0]/2 + 0.5 * sides[2] * factor - slopeOfBase * factor), (canvasSize[1]/2 - 0.5 * height * factor));
    ctx.fillText("b = " + sides[0] + " cm",(canvasSize[0]/2 + 0.5 * sides[2] * factor + canvasSize[0]/2 + 0.5 * sides[2] * factor - slopeOfBase * factor) / 2 + 50,(canvasSize[1]/2 + 0.5 * height * factor + canvasSize[1]/2 - 0.5 * height * factor) / 2);
    ctx.lineTo((canvasSize[0]/2 - 0.5 * sides[2] * factor), (canvasSize[1]/2 + 0.5 * height * factor));
    ctx.fillText("a = " + sides[1] + " cm",(canvasSize[0]/2 + 0.5 * sides[2] * factor - slopeOfBase * factor + canvasSize[0]/2 - 0.5 * sides[2] * factor) / 2 - 50,(canvasSize[1]/2 - 0.5 * height * factor + canvasSize[1]/2 + 0.5 * height * factor) / 2);
    ctx.stroke();
    				
    ctx.beginPath();
    ctx.setLineDash([5]);
    ctx.moveTo((canvasSize[0]/2 + 0.5 * sides[2] * factor - slopeOfBase * factor), (canvasSize[1]/2 - 0.5 * height * factor));
    ctx.lineTo((canvasSize[0]/2 + 0.5 * sides[2] * factor - slopeOfBase * factor), (canvasSize[1]/2 + 0.5 * height * factor));
    ctx.fillText("h = " + height + " cm",(canvasSize[0]/2 + 0.5 * sides[2] * factor - slopeOfBase * factor + canvasSize[0]/2 + 0.5 * sides[2] * factor - slopeOfBase * factor) / 2,(canvasSize[1]/2 - 0.5 * height * factor + canvasSize[1]/2 + 0.5 * height * factor) / 2 + 20);
    ctx.stroke();

提交回复
热议问题