HTML 5 с использованием холста - PullRequest
0 голосов
/ 04 марта 2019

unction calculate() {
var base = document.getElementById("base1").value;
var height = document.getElementById("altura").value;
 var base1=  document.getElementById("base1").value;
var height1 =  document.getElementById("height1").value;
 
  var area = base * height / 2;
  document.getElementById("area").innerHTML = area;
  
}


var ctx = document.getElementById("canvas").getContext("2d");

var base = base1 * 100; 
var height = height1* 100; 
ctx.moveTo(0, 0);
ctx.lineTo(base, 0); 

ctx.moveTo(base, 0); 
ctx.lineTo(base / 2, height);

ctx.moveTo(base / 2, height);
ctx.lineTo(0, 0);
ctx.stroke(); 
<!DOCTYPE html>
<html>
  <head>
    <title>Triangle</title>
  </head>
  <body>
   <!-- This is the HTML5 canvas. We need to specify the its width and height but feel free to change them -->
 <canvas id="canvas" width=400 height=300></canvas>
<input id="base1" placeholder="Input base1 length">
<input id="height1" placeholder="Input height1 length">
<button type="button" id="submit" onclick="calculate()">Calculate</button>
   <p>The area is <span id="area"></span></p>
    
 </body>
</html>

У меня вопрос, я строю веб-сайт, и мне нужно представить площадь треугольника на основе уравнения Area = bh/2 Япытаясь использовать canvas для генерации формы, я много искал кусок кода, который мог бы использовать, но пока ничего.

Пока что я создал 3 переменные.

var base

var height 

Я нарисовал треугольник отдельно от этих 2 переменных, используя canvas - однако на этой странице пользователь должен заполнить базу ивысота путем ввода чисел, которые он хотел бы рассчитать, и я не нашел способа сопоставить идеи вокруг этого.

Пожалуйста, помогите.

1 Ответ

0 голосов

Чтобы использовать холст HTML5, вам нужно сначала создать элемент холста в своем коде HTML, а затем получить его в своем коде JS с помощью document.getElementById ().

Затем вам нужно получить ссылку на2d контекст, используя canvas.getContext("2d"), чтобы вы могли использовать его для рисования на холсте.Затем вы определяете свой путь треугольника, используя следующие функции: ctx.moveTo() и ctx.lineTo().

Я предлагаю вам прочитать об этом здесь: https://www.w3schools.com/html/html5_canvas.asp или здесь: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial

В любом случае следующий код может удовлетворить ваши потребности:

var ctx = document.getElementById("canvas").getContext("2d"); // Get the 2d context which we will use for drawing

var base = 100; // Your base length
var height = 100; // Your height length

//TIP: I suggest multiplying them by some variable so that they look bigger

ctx.moveTo(0, 0); // This methods move an imaginary "pen" to the location 0, 0
ctx.lineTo(base, 0); // And this method moves that imaginary "pen" to the location base, 0 while also creating a line between those points.

ctx.moveTo(base, 0); // We start the next line at the end of the base
ctx.lineTo(base / 2, height); // And we finish it at the middle point of the base but height pixels below it and that's why the triangle will be isosceles triangle(2 of its sides will be equal)

ctx.moveTo(base / 2, height); // And the final line begins and the end of the previous
ctx.lineTo(0, 0); // And ends in the beggining of the first

// Basically we define a path from (0, 0) to (base, 0) to (base / 2, height) to (0, 0) which closes your triangle 

ctx.stroke(); // This method colors the path so that the triangle won't appear white
<!DOCTYPE html>
<html>
  <head>
    <title>Triangle</title>
  </head>
  <body>
    <!-- This is the HTML5 canvas. We need to specify the its width and height but feel free to change them -->
    <canvas id="canvas" width=400 height=300></canvas>
  </body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...