canvas Javascript 上未显示框

Box not showing on canvas Javascript

我目前正在创建一个类似于绘画的软件,但是我一直坚持要让一个框跟随 canvas 上的鼠标。该框的目的是让它显示鼠标位置,显示已选择的颜色以及显示画笔的大小。我在网上找到了这段代码:

<html>
<head>
<script>
    function m(e){
        var bx = document.getElementById("box");
        bx.style.left = e.pageX;
        bx.style.top = e.pageY;

    }
</script>
</head>

<body onmousemove="m(event)">
    <div id="box" style="background-color:#990000; width:20px; height:20px; position:absolute;" />
</body>

我已经尝试将它实现到我的程序中,但是它似乎没有显示在 canvas...我已经将函数 m(e) 更改为 fnTrackMouse(event)

我只能主要使用javascript和一点html和css。没有 Jquery 请。这是我正在处理的程序的一部分:

<!doctype html>
<html lang="en">
<head>
<style>
...
</style>

<script>
        var oCanvas, oCanvasContext; //declare the global variables used to hold and control the canvas element
        var sFillColour; //create a global variable used to hold the active/selected colour
        var sCanvasColour; //create a global variable used to hold the canvas colour
        var iMouseX, iMouseY; //declare the global variables used to hold the mouse's coordinates
        var iBrushWidth, iBrushHeight; //declare the global variables used to hold the selected brush sizes

        function fnInitialise(iCanvasWidth, iCanvasHeight) {
            //this function is called via the HTML body tag and the onload event
            fnDebugMessage("Running fnInitialise"); //debug message
            oCanvas = document.getElementById("cw1Canvas"); //create a reference to the HTML canvas element
            if (oCanvas.getContext) { //test to see if we can read the canvas' context; if true we have found the canvas
                oCanvas.width=iCanvasWidth; //set the canvas width using the width argument passed to the fnInitialise function
                oCanvas.height=iCanvasHeight; //set the canvas height using the width argument passed to the fnInitialise function
                oCanvasContext = oCanvas.getContext("2d"); //set the context to 2D
                fnDebugMessage("Canvas size, width: " + iCanvasWidth + ", height: " + iCanvasHeight); //debug message, if this message appears in 

                //set some default values`
                sCanvasColour=getComputedStyle(oCanvas).getPropertyValue("background-color"); //this instruction automatically detects the background colour of the cavas and stores it in the global sCanvasColour variable
                fnDebugMessage("Canvas background colour: " + sCanvasColour); //debug message, if this message appears in 

                //let set a default brush size
                iBrushWidth=5;
                iBrushHeight=5;

                //set the canvas size to 550px x 550px
                oCanvas.width=550;
                oCanvas.height=550;

            } else {
                fnDebugMessage("fnInitialise, failed to get the canvas's context"); //debug message, we were unable to get the canvas' context
            }   
        }

        function fnTrackMouse(e) {
            //this function is called "everytime" the user's mouse is moved when over the associated element (in this case the canvas)
            //we have also added the ability for it to accept a parameter (called e, actually we can call it anything but as event is a reserved work "e" makes some sense
            var canvasRect = oCanvas.getBoundingClientRect(); //use this function to dynamically get the size of the canvas and its position
            iMouseX=(e.clientX - canvasRect.left - 3); //modify the original position of the mouse by accounting for the position on the canvas; on the x
            iMouseY=(e.clientY - canvasRect.top - 3); //modify the original position of the mouse by accounting for the position on the canvas; on the y

            var bx = document.getElementById("box");
            bx.style.left = iMouseX;
            bx.style.top = iMouseY;
            fnDebugMessage("Working!"+iMouseX)


            if (e.buttons==1) { //this checks to see if the user is pressing the left mouse button (1 = the left mouse button)
                //the user has pressed the left button - so lets start painting
                fnPaint(iMouseX, iMouseY, iBrushWidth, iBrushHeight); //call the fnPaint function and pass it the coordinates and size to paint
            }

            fnDebugMessage("Tracking mouse: x: " + iMouseX + ", y: "+iMouseY); //update the console to show the mouse position, dont forget, you may need to include an offset to centre the paint effect               

        }
    </script>

</head>
<body onload="fnInitialise(100, 100);">

    <!-- 
        this div block (HTML page divider) is used to hold the entire interactive painting HTML elements 
        the benefit of putting multiple elements in a single container is that if you set the location of the 
        container each of the elements held by the container will move relative to it; move one, move all 
    -->
    <div id="cw1MainContainer">


        <!-- this div block is only used to hold the HTML canvas element -->
        <div id="cw1CanvasContainer">
            <canvas id="cw1Canvas" onmousemove="fnTrackMouse(event);" onkeypress="fnBrushSize(event);"></canvas>
            <div id="box" style="background-color:#990000; width:20px; height:20px; position:absolute;" />
            <!-- 
                by specifing the onmouseover event the canvas will call the "fnTrackMouse" function EVERY time the 
                mouse moves 1 pixel over the canvas.
                by passing the JavaScript "event" we are effectively also passing details about the event, 
                e.g. where the mouse was, what buttons were pressed etc. 
            -->
        </div>
   </div>       

</body>
</html>

我已经把我认为与这个问题无关的大部分代码都去掉了,但如果有必要,请告诉我。任何帮助,将不胜感激。干杯

你的代码有点问题。

此处您试图根据鼠标位置设置 bx 元素的位置:

    bx.style.left = iMouseX;
    bx.style.top = iMouseY;

不幸的是,这不起作用,除非您附加字符串 px - 像素的缩写形式。

    bx.style.left = iMouseX+"px";
    bx.style.top = iMouseY+"px";

您的问题是您没有为您的职位提供单位。您可以通过将 px 后缀附加到您的鼠标位置坐标来解决此问题:

bx.style.left = iMouseX +'px';
bx.style.top = iMouseY + 'px';

但是,您仍然会遇到问题。这里的问题是您的 canvas 正在侦听 onmousemove 事件。但是,当您将 "box" div 移动到您的鼠标位置时,canvas 的 onmousemove 事件将不会被触发,直到您将鼠标移出框并且回到 canvas,从而产生 "lagging behind" 效果。要解决此问题,您可以将样式 pointer-events: none 添加到框 div,这将停止框上的所有鼠标事件。

参见下面的示例:

canvas {
  border: 1px solid black;
}

#box {
  pointer-events: none;
}
<!doctype html>
<html lang="en">
<head>
  <script>
    var oCanvas, oCanvasContext;
    var sFillColour;
    var sCanvasColour;
    var iMouseX, iMouseY;
    var iBrushWidth, iBrushHeight;
    var multiplier = 1

    function fnInitialise(iCanvasWidth, iCanvasHeight) {

      oCanvas = document.getElementById("cw1Canvas");
      if (oCanvas.getContext) {
        oCanvas.width = iCanvasWidth;
        oCanvas.height = iCanvasHeight;
        oCanvasContext = oCanvas.getContext("2d");

        sCanvasColour = getComputedStyle(oCanvas).getPropertyValue("background-color");
        iBrushWidth = 5;
        iBrushHeight = 5;
      } else {
      }
    }

    function fnTrackMouse(e) {
      var canvasRect = oCanvas.getBoundingClientRect();
      iMouseX = (e.clientX - canvasRect.left - 3);
      iMouseY = (e.clientY - canvasRect.top - 3);

      var bx = document.getElementById("box");
      bx.style.left = iMouseX +'px';
      bx.style.top = iMouseY + 'px';

      if (e.ctrlKey) {
        fnSetFillColour(sCanvasColour);
      }
      
      if (e.buttons == 1) {
        fnPaint(iMouseX, iMouseY, iBrushWidth, iBrushHeight);
      }
    }
  </script>

</head>

<body onload="fnInitialise(100, 100);">
  <div id="cw1MainContainer">
    <div id="cw1CanvasContainer">
      <canvas id="cw1Canvas" onmousemove="fnTrackMouse(event);" onkeypress="fnBrushSize(event);"></canvas>
      
      <div id="box" style="background-color:#990000; width:20px; height:20px; position:absolute;" />

    </div>
  </div>
</body>
</html>