如何使自定义绘制按钮在html5画布上工作 [英] How to make custom drawn buttons on html5 canvas work

查看:195
本文介绍了如何使自定义绘制按钮在html5画布上工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个html游戏,并希望添加屏幕上的按钮。

I am making a html game and want to add onscreen buttons.

要做到这一点,我想我需要知道鼠标在点击时的像素。

To do this I think I need to know what pixel the mouse is at when I click.

如果任何人知道如何做,或有另一种方法来制作按钮LMK。

If anyone knows how to do that or has another way to make buttons LMK.

推荐答案

以下是查找鼠标位置的基础知识:


  1. 获取对要监听鼠标事件的DOM元素的引用。

  1. Get a reference to the DOM element on which you want to listen for mouse events.

var canvas=document.getElementById("canvas");


  • 浏览器报告相对于窗口左上角的鼠标坐标,你的canvas元素,所以你需要解释窗口&画布位置。使用 .getBoundingClientRect 可获取窗口中的canvas元素的偏移量。

  • The browser reports mouse coordinates relative to the top-left of the window rather than relative to your canvas element, so you need to account for the difference between the window & canvas positions. Use .getBoundingClientRect to fetch the offset of the canvas element within the window.

    // save the canvas offset in global variables
    var BB=canvas.getBoundingClientRect();
    var BBoffsetX=BB.left;
    var BBoffsetY=BB.top;
    


  • 告诉浏览器,当用户使用鼠标订阅时到鼠标事件。你可以使用 .onmousedown,.onmousemove,.onmouseup&

  • Tell the browser you want to be told when the user does something with the mouse by subscribing to mouse events. You can do this using .onmousedown, .onmousemove, .onmouseup & .onmouseout and giving the browser functions to execute when these events occur.

    // listen for mousedown events, call handleMousedown() when they occur
    // listen for mousemove events, call handleMousemove() when they occur
    // listen for mouseup events, call handleMouseup() when they occur
    // listen for mouseout events, call handleMouseout() when they occur
    
    canvas.onmousedown=handleMousedown;
    canvas.onmousemove=handleMousemove;
    canvas.onmouseup=handleMouseup;
    canvas.onmouseout=handleMouseup;
    


  • 通过编写鼠标处理程序函数来响应鼠标事件。浏览器将在执行处理程序时自动发送 mouseevent 参数。该mouseevent包含 clientX& clientY 属性,它们是相对于可见客户端区域左上角的X,Y坐标。要在画布中获取鼠标位置 ,您必须减去 BBoffsetX&

  • Respond to mouse events by coding mouse handler functions. The browser will automatically send an mouseevent argument when it executes the handler. That mouseevent contains clientX & clientY properties which are the X,Y coordinates relative to the top-left corner of the visible client area. To get the mouse position inside the canvas you must subtract BBoffsetX & BBoffsetY which were calculated in step#2.

    // this function is called every time the user presses the mouse down.
    // "e" is the mouseevent argument the browser automatically sends 
    function handleMousedown(e){
         // calculate the mouse position RELATIVE TO THE CANVAS
         var mouseX=e.clientX-BBoffsetX;
         var mouseY=e.clientY-BBoffsetY;
    
         // you have the mouse position so now do your button stuff
    }
    


  • 窗口将被滚动时的细化...如果页面内容大于将适合浏览器显示区域,浏览器将添加滚动条,让用户滚动查看所有页面内容。当窗口滚动时,您在步骤#2中计算的偏移将无效,因此必须重新计算。您可以订阅 window.onscroll 事件,并在滚动发生时重新计算偏移量。

  • A refinement if the window will be scrolled...If the page content is larger than will fit in the browser display area, the browser will add scrollbars to let the user scroll to view all the page content. When the window scrolls, your offsets calculated in step#2 will become invalid so they must be recalculated. You can subscribe to the window.onscroll event and recalculate the offsets when scrolling occurs.

    // listen for events that invalidate the canvas offsets
    window.onscroll=function(e){ setBB(); }
    window.onresize=function(e){ setBB(); }
    
    // recalculate the offsets
    function setBB(){
        BB=canvas.getBoundingClientRect();
        BBoffsetX=BB.left;
        BBoffsetY=BB.top;
    }        
    


  • 您的自定义按钮

    这是一个简单的按钮系统...

    Here's a simple button system...


    • 它显示(非常)简单的自定义绘制按钮

    • 它还显示了当鼠标事件发生时如何获取鼠标点击位置,


    • 重新绘制「点击」按钮,表示该按钮已按下或已释放。

    • It displays (very!) simple custom drawn buttons,
    • It also shows how to get the mouse click position when mouse events occur,
    • It shows how to hit-test which custom drawn button the mouse is over,
    • It redraws the "hit" button to indicate it is pressed or released.

    ...欢迎您开始使用它...

    ...You're welcome to start with it...

    var $clicked=$('#clicked');
    
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    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(); }
    
    var clickedButton;
    var buttons=[];
    buttons.push(makeButton(1,20,20,50,20,'One','skyblue','gray','black',
        function(){ $clicked.text('You clicked: '+this.id+' with label: '+this.label); },
        function(){ $clicked.text('You released: '+this.id+' with label: '+this.label); }
    ));
    buttons.push(makeButton(2,20,50,50,20,'Two','lightgreen','gray','black',
        function(){ $clicked.text('You clicked: '+this.id+' with label: '+this.label); },
        function(){ $clicked.text('You released: '+this.id+' with label: '+this.label); }
    ));
    
    //
    drawAll();
    
    //
    $("#canvas").mousedown(function(e){handleMouseDown(e);});
    $("#canvas").mouseup(function(e){handleMouseUpOut(e);});
    $("#canvas").mouseout(function(e){handleMouseUpOut(e);});
    
    
    function makeButton(id,x,y,w,h,label,fill,stroke,labelcolor,clickFn,releaseFn){
        return({
            id:id,
            x:x, y:y, w:w, h:h,
            fill:fill, stroke:stroke, labelcolor:labelcolor,
            label:label,
            click:clickFn,
            release:releaseFn
        });
    }
    
    function drawAll(){
        for(var i=0;i<buttons.length;i++){
            drawButton(buttons[i],false);
        }
    }
    
    function drawButton(b,isDown){
        ctx.clearRect(b.x-1,b.y-1,b.w+2,b.h+2);
        ctx.fillStyle=b.fill;
        ctx.fillRect(b.x,b.y,b.w,b.h);
        ctx.strokeStyle=b.stroke;
        ctx.strokeRect(b.x,b.y,b.w,b.h);
        ctx.textAlign='center';
        ctx.textBaseline='middle';
        ctx.fillStyle=b.labelcolor;
        ctx.fillText(b.label,b.x+b.w/2,b.y+b.h/2);
        if(isDown){
            ctx.beginPath();
            ctx.moveTo(b.x,b.y+b.h);
            ctx.lineTo(b.x,b.y);
            ctx.lineTo(b.x+b.w,b.y);
            ctx.strokeStyle='black';
            ctx.stroke();
        }
    }
    
    function findButton(mx,my){
        for(var i=0;i<buttons.length;i++){
            var b=buttons[i];
            if(mx>b.x && mx<b.x+b.w && my>b.y && my<b.y+b.h){
                return(buttons[i]);
            }
        }
        return(null);
    }
    
    function handleMouseDown(e){
      // tell the browser we're handling this event
      e.preventDefault();
      e.stopPropagation();
      
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
    
      // check if a button was clicked under the mouse
      var b=findButton(mouseX,mouseY);
      if(b){
          clickedButton=b;
          drawButton(b,true);
          b.click();
      }
    }
    
    function handleMouseUpOut(e){
      // tell the browser we're handling this event
      e.preventDefault();
      e.stopPropagation();
      
      // release any clicked button
      if(clickedButton){
          drawButton(clickedButton,false);
          clickedButton.release();
          clickedButton=null;
      }
    }

    body{ background-color: ivory; }
    #canvas{border:1px solid red; }

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <h4 id=clicked>Click a button.</h4>
    <canvas id="canvas" width=300 height=300></canvas>

    这篇关于如何使自定义绘制按钮在html5画布上工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆