如何解决将高亮或标记功能添加到带有javascript的html canvas
我正在制作核物理网页游戏。我在画布上创建了一个核素图。我手动创建了每个同位素,并输入了相应的同位素名称。下面是一个样本,因为有500多个同位素。我必须手动执行此操作,因为“栅格”必须采用正常核素图的形式。我接下来要做的是创建某种功能,该功能将在单击时突出显示同位素,或者在单击时在同位素上放置“标记”。单击其他同位素时,取消突出显示或移动标记。我已经参加了很长一段时间,但是我无法弄清楚。有人知道我该怎么做到吗?
// hydrogen
ctx.fillRect(21,960,25,25);
ctx.fillRect(46,25);
ctx.strokeRect(71,25);
ctx.strokeRect(96,25);
ctx.strokeRect(121,25);
ctx.strokeRect(146,25);
ctx.strokeRect(171,25);
//
ctx.fillStyle = 'white';
ctx.fillText("1H",23,980,15,15);
ctx.fillStyle = 'white';
ctx.fillText("2H",48,15);
ctx.fillStyle = 'black';
ctx.fillText("3H",73,15);
ctx.fillStyle = 'black';
ctx.fillText("4H",98,15);
ctx.fillStyle = 'black';
ctx.fillText("5H",123,15);
ctx.fillStyle = 'black';
ctx.fillText("6H",148,15);
ctx.fillStyle = 'black';
ctx.fillText("7H",173,15);
解决方法
在这里,我创建了一个演示如何演示如何创建 hitbox 的演示。脚本运行时,点击框将由一个在画布上具有随机位置的正方形表示。
在脚本中,我们使用mousedown
和mouseup
事件侦听器来确定用户何时按下和释放鼠标。按下鼠标时,将根据画布的大小计算鼠标的x
和y
坐标。通过这种方式进行计算,您可以获得在画布上被单击的确切像素。然后将其存储在全局变量中。
您需要知道点击框的x
,y
,width
和height
,因为您需要确定x
是否并且点击的y
位于点击框的正方形内。
在下面的演示中,每当您单击并释放该单击时,都会重新渲染视图。 mouseData
状态更改将在新渲染中显示。然后,如果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 && x <= square.x + square.width) &&
(y >= square.y && 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,width,height } = square; // Get all dimensions of the square.
const { clicked,position } = mouseData; // Get data of the mouse.
context.clearRect(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 && isInHitbox(position,square)) {
context.fillStyle = 'green';
}
// Draw the hitbox.
context.fillRect(x,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>
,
我创建了这些功能,以在画布上绘制一个圆并能够跟踪鼠标的位置,测试鼠标是否在圆上,然后侦听上下左右的点击以将其拖动。如果项目中还有其他绘制元素,那么在我看来,这就是我所有的520种同位素,您只需要将该代码放入redraw函数中,否则在移动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 & Y (mx & 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,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,Math.PI*2);
ctx.fillStyle=shape.color;
ctx.fill();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。