我正在尝试在画布上创建一个三角形。但是我不确定哪一侧是x1,y1,x2,y2 ...等。我正在将三角形与此website上给出的三角形匹配。但是我看到了不同的结果。这是我的JSFiddle
这是我的代码:
var canvasElement = document.querySelector("#canvas");
var ctx = canvasElement.getContext("2d");
// Sides: a = 30 b = 30 c = 59
var triangle = {
x1: 30,
y1: 0,
x2: 0,
y2: 59,
x3: 30,
y3: 59
}
ctx.strokeStyle = 'red';
ctx.beginPath();
ctx.moveTo(triangle.x1, triangle.y1);
ctx.lineTo(triangle.x2, triangle.y2);
ctx.lineTo(triangle.x3, triangle.y3);
ctx.lineTo(triangle.x1, triangle.y1);
ctx.closePath();
ctx.stroke();
<canvas id="canvas" width="300" height="300"></canvas>
最佳答案
var canvasElement = document.querySelector("#canvas");
var ctx = canvasElement.getContext("2d");
// Sides: a = 30 b = 30 c = 59
var triangle = {
x1: 30,
y1: 0,
x2: 0,
y2: 59,
x3: 30,
y3: 59
}
ctx.strokeStyle = 'red';
ctx.beginPath();
ctx.moveTo(triangle.x1, triangle.y1);
ctx.lineTo(triangle.x2, triangle.y2);
ctx.lineTo(triangle.y2, triangle.y2);
ctx.closePath();
ctx.stroke();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="canvas" width="300" height="300"></canvas>
// JavaScript for drawing on canvas
// applying colors + three triangles
function draw() {
// canvas with id="myCanvas"
var canvas = document.getElementById('myCanvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.strokeStyle = "#00F";
ctx.moveTo(400, 0);
ctx.lineTo(300, 200); // draw straight down by 200px (200 + 200)
ctx.lineTo(500, 200); // draw up toward left (100 less than 300, so left)
ctx.closePath(); // connect end to start
ctx.stroke(); // outline the shape that's been described
}
}
draw();
<canvas id="myCanvas" width="700" height="410">
<p>Some default content can appear here.</p>
</canvas>
<p>Triangles!</p>
关于javascript - 如何在Javascript中在 Canvas 上以编程方式绘制三 Angular 形?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54805017/