javascript - 如何使用我的代码让鼠标悬停在带有事件监听器的 html Canvas 上绘制? https ://jsfiddle. 网/dannixx/d0p0j8cL/

标签 javascript html canvas

如何使用我的代码让鼠标悬停在带有事件监听器的 html Canvas 上绘制? https://jsfiddle.net/dannixx/d0p0j8cL/ jifiddle 文件,我希望能够用鼠标悬停在 Canvas 上画线 https://jsfiddle.net/dannixx/d0p0j8cL/

  <!DOCTYPE html>
<html>

<head>
    <title>Canvas</title>
    <style type="text/css">
        #Canvas1 {

        border: : dotted 3px black;
        background-color: blue;    


        }

    </style>

    <script>

       window.onload = function(){

           var theCanvas = document.getElementById("Canvas1");

    if (theCanvas && document.getContext("2d")){
     var ctx = theCanvas.getContext("2d";)
     if(ctx){
         ctx.fillStyle = "lightblue";
         ctx.fillRect(0,0 ctx.canvas.width, ctx.canvas.height)


     }


       } 
    }




    </script>
    </head>

<body>
    <h1>cnavas</h1>
    <p>ex</p>
    <canvas id="Canvas1" width="400", height="300"></canvas>





<p id="demo"></p>


    </body>

</html>

最佳答案

这是一个非常简单的示例,它使用 onmousemove 监听器来更新新的鼠标坐标并从先前的坐标绘制一条线到新的坐标。运行它看看!

   var x = null;
   var y = null;
   var c = null;
   var ctx = null;


function getPos(e) {
         //if it is the first time the event listener is called then set x and y to the new mouse coordinate
         if(x == null) {
             x=e.clientX;
             y=e.clientY;
           }
         //otherwise draw from the previous point (x, y) to the new coordinates (e.clientX, e.clientY).

         ctx.beginPath();
         ctx.moveTo(x,y);
         ctx.lineTo(e.clientX,e.clientY);
         ctx.stroke();
         x=e.clientX;
         y=e.clientY;
    	}
     
 
      window.onload = function(){
       c=document.getElementById("Canvas1");
       ctx=c.getContext("2d");
    }
<canvas onmousemove="getPos(event)" id="Canvas1" width="400", height="300"></canvas>

关于javascript - 如何使用我的代码让鼠标悬停在带有事件监听器的 html Canvas 上绘制? https ://jsfiddle. 网/dannixx/d0p0j8cL/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40064493/

相关文章:

javascript - 向php发送ajax请求无数据响应

javascript - 如何检索可视化放置在 div 下的元素

javascript - 如何定位 firebase 中某个节点的子节点?

javascript - 使用 React 和 setTimeout 更新 <canvas/>

javascript - 为什么 canvas.arc 不工作?

javascript - ASP.NET MVC : difference between dropdown & textbox onchange event

SilverStripe 网格字段扩展重新排序后的 JavaScript 回调?

javascript - 如何将禁用的内部样式节点添加到 HTML5 DOM?

html - 我正在尝试为我的图像提供 "box-shadow",但我不工作

javascript - 如何检测对象是否位于 Canvas 元素的坐标处?