#javascript #html #html5-canvas
#javascript #HTML #html5-canvas
Вопрос:
Я работаю над созданием веб-игры по ядерной физике. Я создал диаграмму нуклидов на холсте. Я вручную создал каждый изотоп и ввел их соответствующее имя изотопа. Ниже приведен пример, поскольку существует более 500 изотопов. Мне пришлось сделать это вручную, потому что «сетка» должна быть в форме обычной диаграммы нуклидов. Что мне нужно сделать дальше, это создать какую-то функцию, которая будет либо выделять изотоп при нажатии на него, либо ставить «маркер» на изотоп при нажатии. И отключите подсветку или переместите маркер при нажатии на другой изотоп. Я занимаюсь этим уже довольно давно, но не могу понять. Кто-нибудь знает, как я могу этого добиться?
// hydrogen
ctx.fillRect(21, 960, 25, 25);
ctx.fillRect(46, 960, 25, 25);
ctx.strokeRect(71, 960, 25, 25);
ctx.strokeRect(96, 960, 25, 25);
ctx.strokeRect(121, 960, 25, 25);
ctx.strokeRect(146, 960, 25, 25);
ctx.strokeRect(171, 960, 25, 25);
//
ctx.fillStyle = 'white';
ctx.fillText("1H", 23, 980, 15, 15);
ctx.fillStyle = 'white';
ctx.fillText("2H", 48, 980, 15, 15);
ctx.fillStyle = 'black';
ctx.fillText("3H", 73, 980, 15, 15);
ctx.fillStyle = 'black';
ctx.fillText("4H", 98, 980, 15, 15);
ctx.fillStyle = 'black';
ctx.fillText("5H", 123, 980, 15, 15);
ctx.fillStyle = 'black';
ctx.fillText("6H", 148, 980, 15, 15);
ctx.fillStyle = 'black';
ctx.fillText("7H", 173, 980, 15, 15);
Комментарии:
1. Возможно, дайте каждому изотопу хитбокс . Как невидимый квадрат вокруг вашего изотопа. Затем прослушайте
click
событие на холсте и проверьте, соответствуют ли координаты мыши каким-либо границам хитбоксов.2. Я никогда раньше не использовал хитбокс, как бы я это написал?
3. Не прямой ответ, но я думаю, что вы усложняете ситуацию больше, чем нужно. Canvas 2D — это пример рендеринга в немедленном режиме , который делает интерактивность, как вы описываете, нетривиальной. Если вы действительно не хотите создавать пользовательскую систему пользовательского интерфейса с нуля, я бы рекомендовал использовать узлы DOM для ваших isotopes CSS styling JS для интерактивности. Или используйте библиотеку поверх canvas, такую как EaselJS , которая обеспечивает взаимодействие с мышью и иерархию объектов для представления вашего пользовательского интерфейса.
Ответ №1:
Здесь я создал демонстрацию того, как вы могли бы сделать такую вещь, как создание хитбокса. Хитбокс будет представлен квадратом, который имеет случайную позицию на холсте при запуске скрипта.
В скрипте мы используем mousedown
mouseup
прослушиватели событий и, чтобы определить, когда пользователь нажимает и отпускает мышь. При наведении курсора x
мыши и y
координаты мыши вычисляются относительно размера холста. Вычисляя его таким образом, вы можете получить точный пиксель на холсте, на который был нажат. Затем он сохраняет это значение в глобальной переменной.
Вам нужно будет знать x
, y
, width
и height
хитбокса, потому что вы захотите определить, находится ли x
и y
щелчка внутри квадрата, который является хитбоксом.
В приведенной ниже демонстрации вид отображается повторно всякий раз, когда вы нажимаете и отпускаете щелчок. Изменения mouseData
состояния en покажут это в новом рендеринге. Затем Рендеринг вычисляет хитбокс, если mouseData.position
координаты находятся внутри поля, и изменяет цвет на основе этой оценки.
Затем отпускание мыши запускает еще один повторный рендеринг, меняющий нажатое состояние на false и показывающий исходное состояние хитбокса.
Итак, по сути, это квадрат координат, который определяет, находится ли выбранный пиксель внутри этого квадрата, и что-то делает, если это так.
const canvas = document.querySelector('#canvas');
const context = canvas.getContext('2d');
const squareSideSize = 50;
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
// Stores data on the mouseclick.
let mouseData = {
clicked: false,
position: [] // Here we will store the x and y of click as [ x, y ]
}
/**
* Generates random number between min and max value.
* Just for the purpose of drawing the hitbox.
*/
const getRandomInt = (min, max) => Math.floor(Math.random() * (max - min 1)) min;
/**
* Returns an array with x and y coordinates
* based on the click event.
*/
const getMousePositionOnCanvas = ({ clientX, clientY }) => {
const canvasRect = canvas.getBoundingClientRect();
const x = clientX - canvasRect.left;
const y = clientY - canvasRect.top;
return [ x, y ];
};
/**
* Determines if the x and y from the click is within
* the x, y, width and height of the square.
* Returns true or false.
*/
const isInHitbox = ([ x, y ], square) => (
(x >= square.x amp;amp; x <= square.x square.width) amp;amp;
(y >= square.y amp;amp; y <= square.y square.height)
);
/**
* Create random square.
* This square has an x and y position as well
* as a width and height. The x and y are created
* to enchance the demonstration.
*/
const square = {
x: getRandomInt(0, canvas.width - squareSideSize),
y: getRandomInt(0, canvas.height - squareSideSize),
width: squareSideSize,
height: squareSideSize
};
// Listen for mousedown and update the click position.
canvas.addEventListener('mousedown', event => {
mouseData.clicked = true; // Set clicked state to true.
mouseData.position = getMousePositionOnCanvas(event); // Get the click position relative to the canvas.
render(); // Render with clicked state.
});
// Listen for mousemove and update the position.
canvas.addEventListener('mousemove', event => {
if (mouseData.clicked === true) { // Only act if clicked.
mouseData.position = getMousePositionOnCanvas(event); // Update mouse position.
render(); // Render with updated mouse position.
}
})
// Listen for mouseup and clear the click position.
canvas.addEventListener('mouseup', event => {
mouseData.clicked = false; // Set clicked state to false.
mouseData.position.length = 0; // Reset the positions.
render(); // Render unclicked state.
});
/**
* Render function which clears and draws on the canvas.
* Here we determine what to draw according the data we
* collection from the mouse.
*/
function render() {
requestAnimationFrame(() => {
const { x, y, width, height } = square; // Get all dimensions of the square.
const { clicked, position } = mouseData; // Get data of the mouse.
context.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas for a clean re-render.
// Default white color.
context.fillStyle = 'white';
// Check if the mouse has clicked and if the
// position is inside the hitbox. Change the color
// if a it is true.
if (clicked === true amp;amp; isInHitbox(position, square)) {
context.fillStyle = 'green';
}
// Draw the hitbox.
context.fillRect(x, y, width, height);
});
}
// Initial render.
render();
html,
body {
width: 100%;
height: 100%;
margin: 0;
box-sizing: border-box;
}
body {
padding: 10px;
}
canvas {
width: 100%;
height: 100%;
background: #000000;
}
<canvas id="canvas"></canvas>
Ответ №2:
Я создал эти функции, чтобы нарисовать круг на моем холсте и иметь возможность отслеживать положение мыши, проверять, находится ли она на круге, а затем прослушивать щелчки вниз и вверх, чтобы иметь возможность перетащить его. Если в проекте есть другие элементы рисования, в данном случае для меня это все 520 моих изотопов, вам просто нужно поместить этот код внутрь вашей функции перерисовки, иначе все остальное исчезнет после перемещения cirlce
var cw=canvas.width;
var ch=canvas.height;
document.body.appendChild(canvas);
// used to calc canvas position relative to window
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
canvas.onresize=function(e){ reOffset(); }
// save relevant information about shapes drawn on the canvas
var shapes=[];
// define one circle and save it in the shapes[] array
shapes.push( {x:300, y:275, radius:10} );
var isDragging=false;
var startX,startY;
// hold the index of the shape being dragged (if any)
var selectedShapeIndex;
// draw the shapes on the canvas
drawAll();
// listen for mouse events
canvas.onmousedown=handleMouseDown;
canvas.onmousemove=handleMouseMove;
canvas.onmouseup=handleMouseUp;
canvas.onmouseout=handleMouseOut;
// given mouse X amp; Y (mx amp; my) and shape object
// return true/false whether mouse is inside the shape
function isMouseInShape(mx,my,shape){
if(shape.radius){
// this is a circle
var dx=mx-shape.x;
var dy=my-shape.y;
// math test to see if mouse is inside circle
if(dx*dx dy*dy<shape.radius*shape.radius){
// yes, mouse is inside this circle
return(true);
}
}
// the mouse isn't in any of the shapes
return(false);
}
function handleMouseDown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// calculate the current mouse position
startX=parseInt(e.clientX-offsetX);
startY=parseInt(e.clientY-offsetY);
// test mouse position against all shapes
// post result if mouse is in a shape
for(var i=0;i<shapes.length;i ){
if(isMouseInShape(startX,startY,shapes[i])){
// the mouse is inside this shape
// select this shape
selectedShapeIndex=i;
// set the isDragging flag
isDragging=true;
// and return (==stop looking for
// further shapes under the mouse)
return;
}
}
}
function handleMouseUp(e){
// return if we're not dragging
if(!isDragging){return;}
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// the drag is over -- clear the isDragging flag
isDragging=false;
}
function handleMouseOut(e){
// return if we're not dragging
if(!isDragging){return;}
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// the drag is over -- clear the isDragging flag
isDragging=false;
}
function handleMouseMove(e){
// return if we're not dragging
if(!isDragging){return;}
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// calculate the current mouse position
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// how far has the mouse dragged from its previous mousemove position?
var dx=mouseX-startX;
var dy=mouseY-startY;
// move the selected shape by the drag distance
var selectedShape=shapes[selectedShapeIndex];
selectedShape.x =dx;
selectedShape.y =dy;
// clear the canvas and redraw all shapes
drawAll();
// update the starting drag position (== the current mouse position)
startX=mouseX;
startY=mouseY;
}
// clear the canvas and
// redraw all shapes in their current positions
function drawAll(){
ctx.clearRect(0,0,cw,ch);
for(var i=0;i<shapes.length;i ){
var shape=shapes[i];
if(shape.radius){
// it's a circle
ctx.beginPath();
ctx.arc(shape.x,shape.y,shape.radius,0,Math.PI*2);
ctx.fillStyle=shape.color;
ctx.fill();
}
}