如何使用我的代码让鼠标悬停在带有事件监听器的 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/