简体   繁体   English

在画布中动态添加下拉列表

[英]add dropdown dynamically in canvas

I want to create a canvas that allow writing chemical formula the idea is to use hexagone which can be clicked on his summit to change the atom. 我想创建一个允许编写化学式的画布,这个想法是使用六角形,可以点击他的顶峰来改变原子。 So when we click on the hexagone summit a dropdown menu appear in which we can choose the atom. 因此,当我们点击hexagone峰值时,会出现一个下拉菜单,我们可以在其中选择原子。 在此输入图像描述 I can add a dropdown menu as a sibling to the canvas and position it thanks to a container but how could I dynamically (on mouse click) add a dropdown menu on canvas. 我可以将一个下拉菜单作为兄弟添加到画布并通过容器定位它但是我怎么能动态地(在鼠标点击时)在画布上添加一个下拉菜单。

an example of the dropdown menu 下拉菜单的一个示例 在此输入图像描述

Any idea, reflexion are welcome. 任何想法,反思都是受欢迎的。 I've made a simple hexagone which can be the represntation of a cyclohexane for 我做了一个简单的六角形,可以用来代替环己烷 在此输入图像描述 those who have code suggestion 那些有代码建议的人

 var canvas = document.querySelector('#canvas').getContext('2d'),side = 0, size = 100, x = 100, y = 100; canvas.beginPath(); canvas.moveTo(x + size * Math.cos(0), y + size * Math.sin(0)); for (side; side < 7; side++) { canvas.lineTo(x + size * Math.cos(side * 2 * Math.PI / 6), y + size * Math.sin(side * 2 * Math.PI / 6)); } canvas.stroke(); 
 #canvas { width: 200px; height: 200px; } 
 <canvas id="canvas" width="400" height="400"></canvas> 

What I would do is: 我会做的是:

  1. Have an invisible dropdown box already on the page, outside of the canvas element 在画布元素之外的页面上已经有一个不可见的下拉框
  2. On click of the canvas, check and see if the user clicked on a hexagon. 单击画布,检查并查看用户是否单击了六边形。 (check if distance from mouse click is within the bounds of any hexagons on screen) (检查鼠标点击的距离是否在屏幕上任何六边形的范围内)
  3. If it is within the bounds of a hexagon, move the invisible dropdown box to the location of the hexagon and then turn it visible. 如果它在六边形的范围内,则将不可见的下拉框移动到六边形的位置,然后将其变为可见。

If you need an example let me know. 如果您需要一个例子,请告诉我。

I've coded an example in the following CodePen: https://codepen.io/darrylhuffman/pen/OqmBja 我在下面的CodePen中编写了一个示例: https ://codepen.io/darrylhuffman/pen/OqmBja

Here is the logic I am using to determine if the user clicked on an atom, and then to move the dropdown box: 这是我用来确定用户是否点击了一个原子,然后移动下拉框的逻辑:

document.body.addEventListener('mouseup', e => {
    let atom = atoms.find(a => distance(a.position, { x: e.pageX, y: e.pageY}) <= a.r)
    atomDropdown.classList.remove('hidden')
    if(atom){
       atomDropdown.style.left = atom.position.x + 'px'
       atomDropdown.style.top = (atom.position.y + atom.r) + 'px'
    }
})

Be sure to read into all of my code in the CodePen though, because I believe you may want to take the approach I did when it comes to generating atoms/bonds/etc. 请务必阅读CodePen中的所有代码,因为我相信您可能想要采用我在生成原子/键/等方面所采用的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM