less copy protection, more size visualization
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

505 строки
14 KiB

  1. let selected = null;
  2. let selectedEntity = null;
  3. let entityIndex = 0;
  4. let clicked = null;
  5. let dragging = false;
  6. let clickTimeout = null;
  7. let dragOffsetX = null;
  8. let dragOffsetY = null;
  9. let altHeld = false;
  10. const unitChoices = {
  11. length: [
  12. "meters",
  13. "kilometers"
  14. ],
  15. mass: [
  16. "kilograms"
  17. ]
  18. }
  19. const config = {
  20. height: math.unit(10, "meters"),
  21. minLineSize: 50,
  22. maxLineSize: 250
  23. }
  24. const entities = {
  25. }
  26. function constrainRel(coords) {
  27. return {
  28. x: Math.min(Math.max(coords.x, 0), 1),
  29. y: Math.min(Math.max(coords.y, 0), 1)
  30. }
  31. }
  32. function snapRel(coords) {
  33. return constrainRel({
  34. x: coords.x,
  35. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  36. });
  37. }
  38. function adjustAbs(coords, oldHeight, newHeight) {
  39. return { x: coords.x, y: 1 + (coords.y - 1) * math.divide(oldHeight, newHeight) };
  40. }
  41. function rel2abs(coords) {
  42. const canvasWidth = document.querySelector("#display").clientWidth - 50;
  43. const canvasHeight = document.querySelector("#display").clientHeight - 50;
  44. return { x: coords.x * canvasWidth, y: coords.y * canvasHeight };
  45. }
  46. function abs2rel(coords) {
  47. const canvasWidth = document.querySelector("#display").clientWidth - 50;
  48. const canvasHeight = document.querySelector("#display").clientHeight - 50;
  49. return { x: coords.x / canvasWidth, y: coords.y / canvasHeight };
  50. }
  51. function updateEntityElement(entity, element) {
  52. const position = rel2abs({ x: element.dataset.x, y: element.dataset.y });
  53. const view = element.dataset.view;
  54. element.style.left = position.x + "px";
  55. element.style.top = position.y + "px";
  56. const canvasHeight = document.querySelector("#display").clientHeight;
  57. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 100);
  58. element.style.setProperty("--height", pixels + "px");
  59. element.querySelector(".entity-name").innerText = entity.name;
  60. }
  61. function updateSizes() {
  62. drawScale();
  63. Object.entries(entities).forEach(([key, entity]) => {
  64. const element = document.querySelector("#entity-" + key);
  65. updateEntityElement(entity, element);
  66. });
  67. }
  68. function drawScale() {
  69. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  70. let total = heightPer.clone();
  71. total.value = 0;
  72. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  73. drawTick(ctx, 50, y, total);
  74. total = math.add(total, heightPer);
  75. }
  76. }
  77. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  78. const oldStroke = ctx.strokeStyle;
  79. const oldFill = ctx.fillStyle;
  80. ctx.beginPath();
  81. ctx.moveTo(x, y);
  82. ctx.lineTo(x + 20, y);
  83. ctx.strokeStyle = "#000000";
  84. ctx.stroke();
  85. ctx.beginPath();
  86. ctx.moveTo(x + 20, y);
  87. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  88. ctx.strokeStyle = "#aaaaaa";
  89. ctx.stroke();
  90. ctx.beginPath();
  91. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  92. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  93. ctx.strokeStyle = "#000000";
  94. ctx.stroke();
  95. const oldFont = ctx.font;
  96. ctx.font = 'normal 24pt coda';
  97. ctx.fillStyle = "#dddddd";
  98. ctx.beginPath();
  99. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  100. ctx.font = oldFont;
  101. ctx.strokeStyle = oldStroke;
  102. ctx.fillStyle = oldFill;
  103. }
  104. const canvas = document.querySelector("#display");
  105. /** @type {CanvasRenderingContext2D} */
  106. const ctx = canvas.getContext("2d");
  107. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.value;
  108. let heightPer = config.height.clone();
  109. heightPer.value = 1;
  110. if (pixelsPer < config.minLineSize) {
  111. heightPer.value /= pixelsPer / config.minLineSize;
  112. pixelsPer = config.minLineSize;
  113. }
  114. if (pixelsPer > config.maxLineSize) {
  115. heightPer.value /= pixelsPer / config.maxLineSize;
  116. pixelsPer = config.maxLineSize;
  117. }
  118. ctx.clearRect(0, 0, canvas.width, canvas.height);
  119. ctx.scale(1, 1);
  120. ctx.canvas.width = canvas.clientWidth;
  121. ctx.canvas.height = canvas.clientHeight;
  122. ctx.beginPath();
  123. ctx.moveTo(50, 50);
  124. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  125. ctx.stroke();
  126. ctx.beginPath();
  127. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  128. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  129. ctx.stroke();
  130. drawTicks(ctx, pixelsPer, heightPer);
  131. }
  132. function makeEntity() {
  133. const entityTemplate = {
  134. name: "",
  135. author: "",
  136. scale: 1,
  137. views: {
  138. body: {
  139. attributes: {
  140. height: {
  141. name: "Height",
  142. power: 1,
  143. type: "length",
  144. base: math.unit(1, "meter")
  145. },
  146. weight: {
  147. name: "Weight",
  148. power: 3,
  149. type: "mass",
  150. base: math.unit(80, "kg")
  151. }
  152. }
  153. }
  154. },
  155. init: function () {
  156. Object.values(this.views).forEach(view => {
  157. view.parent = this;
  158. Object.entries(view.attributes).forEach(([key, val]) => {
  159. Object.defineProperty(
  160. view,
  161. key,
  162. {
  163. get: function() {
  164. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  165. },
  166. set: function(value) {
  167. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  168. this.parent.scale = newScale;
  169. }
  170. }
  171. )
  172. });
  173. });
  174. delete this.init;
  175. return this;
  176. }
  177. }.init();
  178. return entityTemplate;
  179. }
  180. function clickDown(target, x, y) {
  181. clicked = target;
  182. const rect = target.getBoundingClientRect();
  183. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  184. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  185. dragOffsetX = x - rect.left + entX - rect.width / 2;
  186. dragOffsetY = y - rect.top + entY - rect.height;
  187. clickTimeout = setTimeout(() => { dragging = true }, 200)
  188. }
  189. function clickUp() {
  190. clearTimeout(clickTimeout);
  191. if (clicked) {
  192. if (dragging) {
  193. dragging = false;
  194. } else {
  195. select(clicked);
  196. }
  197. clicked = null;
  198. }
  199. }
  200. function deselect() {
  201. if (selected) {
  202. selected.classList.remove("selected");
  203. }
  204. selected = null;
  205. clearEntityOptions();
  206. clearViewOptions();
  207. }
  208. function select(target) {
  209. deselect();
  210. selected = target;
  211. selectedEntity = entities[target.dataset.key];
  212. selected.classList.add("selected");
  213. entityInfo(selectedEntity, target.dataset.view);
  214. configEntityOptions(selectedEntity);
  215. configViewOptions(selectedEntity, target.dataset.view);
  216. }
  217. function entityInfo(entity, view) {
  218. document.querySelector("#entity-name").innerText = "Name: " + entity.name;
  219. document.querySelector("#entity-author").innerText = "Author: " + entity.author;
  220. document.querySelector("#entity-height").innerText = "Height: " + entity.views[view].height.format({ precision: 3 });
  221. }
  222. function configEntityOptions(entity) {
  223. const holder = document.querySelector("#options-entity");
  224. holder.innerHTML = "";
  225. const scaleLabel = document.createElement("div");
  226. scaleLabel.classList.add("options-label");
  227. scaleLabel.innerText = "Scale";
  228. const scaleRow = document.createElement("div");
  229. scaleRow.classList.add("options-row");
  230. const scaleInput = document.createElement("input");
  231. scaleInput.classList.add("options-field-numeric");
  232. scaleInput.addEventListener("input", e => {
  233. entity.scale = e.target.value;
  234. updateSizes();
  235. });
  236. scaleInput.setAttribute("min", 1);
  237. scaleInput.setAttribute("type", "number");
  238. scaleInput.value = entity.scale;
  239. scaleRow.appendChild(scaleInput);
  240. holder.appendChild(scaleLabel);
  241. holder.appendChild(scaleRow);
  242. const nameLabel = document.createElement("div");
  243. nameLabel.classList.add("options-label");
  244. nameLabel.innerText = "Name";
  245. const nameRow = document.createElement("div");
  246. nameRow.classList.add("options-row");
  247. const nameInput = document.createElement("input");
  248. nameInput.classList.add("options-field-text");
  249. nameInput.value = entity.name;
  250. nameInput.addEventListener("input", e => {
  251. entity.name = e.target.value;
  252. updateSizes();
  253. })
  254. nameRow.appendChild(nameInput);
  255. holder.appendChild(nameLabel);
  256. holder.appendChild(nameRow);
  257. }
  258. function clearEntityOptions() {
  259. const holder = document.querySelector("#options-entity");
  260. holder.innerHTML = "";
  261. }
  262. function configViewOptions(entity, view) {
  263. const holder = document.querySelector("#options-view");
  264. holder.innerHTML = "";
  265. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  266. const label = document.createElement("div");
  267. label.classList.add("options-label");
  268. label.innerText = val.name;
  269. holder.appendChild(label);
  270. const row = document.createElement("div");
  271. row.classList.add("options-row");
  272. holder.appendChild(row);
  273. const input = document.createElement("input");
  274. input.classList.add("options-field-numeric");
  275. input.value = entity.views[view][key].value;
  276. const unit = document.createElement("select");
  277. unitChoices[val.type].forEach(name => {
  278. const option = document.createElement("option");
  279. option.innerText = name;
  280. unit.appendChild(option);
  281. });
  282. input.addEventListener("input", e => {
  283. entity.views[view][key] = math.unit(input.value, unit.value);
  284. updateSizes();
  285. });
  286. unit.addEventListener("input", e => {
  287. entity.views[view][key] = math.unit(input.value, unit.value);
  288. updateSizes();
  289. });
  290. row.appendChild(input);
  291. row.appendChild(unit);
  292. });
  293. }
  294. function clearViewOptions(entity, view) {
  295. const holder = document.querySelector("#options-view");
  296. holder.innerHTML = "";
  297. }
  298. // this is a crime against humanity, and also stolen from
  299. // stack overflow
  300. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  301. const testCanvas = document.createElement("canvas");
  302. testCanvas.id = "test-canvas";
  303. const testCtx = testCanvas.getContext("2d");
  304. function testClick(event) {
  305. const target = event.target;
  306. // Get click coordinates
  307. var x = event.clientX - target.getBoundingClientRect().x,
  308. y = event.clientY - target.getBoundingClientRect().y,
  309. w = testCtx.canvas.width = target.width,
  310. h = testCtx.canvas.height = target.height,
  311. alpha;
  312. // Draw image to canvas
  313. // and read Alpha channel value
  314. testCtx.drawImage(target, 0, 0, w, h);
  315. alpha = testCtx.getImageData(x, y, 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  316. // If pixel is transparent,
  317. // retrieve the element underneath and trigger it's click event
  318. if (alpha === 0) {
  319. const oldDisplay = target.style.display;
  320. target.style.display = "none";
  321. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  322. newTarget.dispatchEvent(new MouseEvent("mousedown", {
  323. "clientX": event.clientX,
  324. "clientY": event.clientY
  325. }));
  326. target.style.display = oldDisplay;
  327. } else {
  328. clickDown(target.parentElement, event.clientX, event.clientY);
  329. }
  330. }
  331. function displayEntity(entity, view, x, y) {
  332. const box = document.createElement("div");
  333. box.classList.add("entity-box");
  334. const img = document.createElement("img");
  335. img.classList.add("entity-image");
  336. const nameTag = document.createElement("div");
  337. nameTag.classList.add("entity-name");
  338. nameTag.innerText = entity.name;
  339. box.appendChild(img);
  340. box.appendChild(nameTag);
  341. img.src = "./man.svg"
  342. box.dataset.x = x;
  343. box.dataset.y = y;
  344. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  345. box.id = "entity-" + entityIndex;
  346. box.dataset.key = entityIndex;
  347. box.dataset.view = view;
  348. entities[entityIndex] = entity;
  349. entityIndex += 1;
  350. const world = document.querySelector("#entities");
  351. world.appendChild(box);
  352. updateEntityElement(entity, box);
  353. }
  354. document.addEventListener("DOMContentLoaded", () => {
  355. for (let x = 0; x < 5; x++) {
  356. const entity = makeEntity();
  357. entity.name = "Dude";
  358. entity.author = "Fen"
  359. const x = 0.25 + Math.random() * 0.5;
  360. const y = 0.25 + Math.random() * 0.5;
  361. displayEntity(entity, "body", x, y);
  362. }
  363. document.querySelector("body").appendChild(testCtx.canvas);
  364. updateSizes();
  365. document.querySelector("#options-height-value").addEventListener("input", e => {
  366. updateWorldHeight();
  367. })
  368. document.querySelector("#options-height-unit").addEventListener("input", e => {
  369. updateWorldHeight();
  370. })
  371. world.addEventListener("mousedown", e => deselect());
  372. document.addEventListener("mouseup", e => clickUp());
  373. });
  374. window.addEventListener("resize", () => {
  375. updateSizes();
  376. })
  377. document.addEventListener("mousemove", (e) => {
  378. if (clicked) {
  379. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  380. clicked.dataset.x = position.x;
  381. clicked.dataset.y = position.y;
  382. updateEntityElement(entities[clicked.dataset.key], clicked);
  383. }
  384. });
  385. function updateWorldHeight() {
  386. const value = Math.max(1, document.querySelector("#options-height-value").value);
  387. const unit = document.querySelector("#options-height-unit").value;
  388. const oldHeight = config.height;
  389. config.height = math.unit(value + " " + unit)
  390. Object.entries(entities).forEach(([key, entity]) => {
  391. const element = document.querySelector("#entity-" + key);
  392. const newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  393. element.dataset.x = newPosition.x;
  394. element.dataset.y = newPosition.y;
  395. });
  396. updateSizes();
  397. }