将高亮或标记功能添加到带有javascript的html canvas

如何解决将高亮或标记功能添加到带有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 的演示。脚本运行时,点击框将由一个在画布上具有随机位置的正方形表示。

在脚本中,我们使用mousedownmouseup事件侦听器来确定用户何时按下和释放鼠标。按下鼠标时,将根据画布的大小计算鼠标的xy坐标。通过这种方式进行计算,您可以获得在画布上被单击的确切像素。然后将其存储在全局变量中。

您需要知道点击框的xywidthheight,因为您需要确定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 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res