Sol*_*ent 80 javascript canvas mouse-position html5-canvas
我试图用鼠标画在HTML5画布上,但它似乎运行良好的唯一方法是如果画布位于0,0(左上角),如果我改变画布位置,由于某种原因它不会像它应该画的那样.这是我的代码.
function createImageOnCanvas(imageId){
document.getElementById("imgCanvas").style.display = "block";
document.getElementById("images").style.overflowY= "hidden";
var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");
var img = new Image(300,300);
img.src = document.getElementById(imageId).src;
context.drawImage(img, (0),(0));
}
function draw(e){
var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");
posx = e.clientX;
posy = e.clientY;
context.fillStyle = "#000000";
context.fillRect (posx, posy, 4, 4);
}
Run Code Online (Sandbox Code Playgroud)
HTML部分
<body>
<div id="images">
</div>
<canvas onmousemove="draw(event)" style="margin:0;padding:0;" id="imgCanvas"
class="canvasView" width="250" height="250"></canvas>
Run Code Online (Sandbox Code Playgroud)
我已经读过有一种方法可以在JavaScript中创建一个简单的函数来获得正确的位置,但我不知道如何做到这一点.
小智 175
对于canvas元素与位图大小相比为1:1的情况,您可以使用以下代码段获取鼠标位置:
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
Run Code Online (Sandbox Code Playgroud)
只需使用事件和画布作为参数从事件中调用它.它返回一个带有x和y的对象,用于鼠标位置.
由于您获得的鼠标位置是相对于客户端窗口,您必须减去canvas元素的位置以将其相对于元素本身进行转换.
代码中的集成示例:
//put this outside the event loop..
var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");
function draw(evt) {
var pos = getMousePos(canvas, evt);
context.fillStyle = "#000000";
context.fillRect (pos.x, pos.y, 4, 4);
}
Run Code Online (Sandbox Code Playgroud)
注意:如果直接应用于canvas元素,边框和填充将影响位置,因此需要考虑这些getComputedStyle()- 或者将这些样式应用于父div.
当存在元素与位图本身不同的情况时,例如,使用CSS缩放元素或者存在像素长宽比等,您将不得不解决此问题.
例:
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect(), // abs. size of element
scaleX = canvas.width / rect.width, // relationship bitmap vs. element for X
scaleY = canvas.height / rect.height; // relationship bitmap vs. element for Y
return {
x: (evt.clientX - rect.left) * scaleX, // scale mouse coordinates after they have
y: (evt.clientY - rect.top) * scaleY // been adjusted to be relative to element
}
}
Run Code Online (Sandbox Code Playgroud)
然后有一个更复杂的情况,你已经将变换应用于上下文,如旋转,倾斜/剪切,缩放,平移等.为了解决这个问题,你可以计算当前矩阵的逆矩阵.
较新的浏览器允许您通过currentTransform属性读取当前矩阵,Firefox(当前alpha)甚至通过提供反转矩阵mozCurrentTransformInverted.然而,Firefox mozCurrentTransform,将返回一个数组,而不是DOMMatrix它应该.当通过实验性标志启用Chrome时,它们都不会返回DOMMatrixa SVGMatrix.
在大多数情况下,然而,你将不得不实现自己的自定义的基质溶液(如自己的解决方案在这里 -免费/ MIT项目),直至该得到充分的支持.
当你最终获得矩阵时,不管你获取矩阵的路径如何,你都需要将其反转并将其应用到鼠标坐标.然后将坐标传递给画布,画布将使用其矩阵将其转换回目前的任何位置.
这样,该点将相对于鼠标处于正确的位置.此外,您还需要将坐标(在应用逆矩阵之前)调整为相对于元素.
仅显示矩阵步骤的示例
function draw(evt) {
var pos = getMousePos(canvas, evt); // get adjusted coordinates as above
var imatrix = matrix.inverse(); // get inverted matrix somehow
pos = imatrix.applyToPoint(pos.x, pos.y); // apply to adjusted coordinate
context.fillStyle = "#000000";
context.fillRect(pos.x-1, pos.y-1, 2, 2);
}
Run Code Online (Sandbox Code Playgroud)
使用上面链接的解决方案的示例(当更广泛支持时替换为本机浏览器解决方案).
实施时使用的一个例子currentTransform是:
var pos = getMousePos(canvas, e); // get adjusted coordinates as above
var matrix = ctx.currentTransform; // W3C (future)
var imatrix = matrix.invertSelf(); // invert
// apply to point:
var x = pos.x * imatrix.a + pos.y * imatrix.c + imatrix.e;
var y = pos.x * imatrix.b + pos.y * imatrix.d + imatrix.f;
Run Code Online (Sandbox Code Playgroud)
更新我做了一个免费的解决方案(MIT),将所有这些步骤嵌入到一个易于使用的对象中,可以在这里找到,并且还可以处理其他一些最容易忽视的细节.
小智 26
您可以使用以下代码段获取鼠标位置:
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: (evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width,
y: (evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height
};
}
Run Code Online (Sandbox Code Playgroud)
此代码考虑了画布空间(evt.clientX - rect.left)的坐标更改以及画布逻辑大小与其样式大小不同时的缩放(/ (rect.right - rect.left) * canvas.width请参阅:HTML5中的画布宽度和高度).
示例:http://jsfiddle.net/sierawski/4xezb7nL/
资料来源:jerryj评论http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
您需要获取鼠标相对于画布的位置
为此,您需要知道画布在页面上的X / Y位置。
这称为画布的“偏移”,这是获取偏移的方法。(我使用jQuery是为了简化跨浏览器的兼容性,但是如果您想使用原始javascript,那么快速的Google也会做到这一点)。
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
Run Code Online (Sandbox Code Playgroud)
然后在鼠标处理程序中,您可以像这样获得鼠标X / Y:
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
}
Run Code Online (Sandbox Code Playgroud)
这是一个说明性的代码和小提琴,显示了如何成功跟踪画布上的鼠标事件:
http://jsfiddle.net/m1erickson/WB7Zu/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#downlog").html("Down: "+ mouseX + " / " + mouseY);
// Put your mousedown stuff here
}
function handleMouseUp(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#uplog").html("Up: "+ mouseX + " / " + mouseY);
// Put your mouseup stuff here
}
function handleMouseOut(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#outlog").html("Out: "+ mouseX + " / " + mouseY);
// Put your mouseOut stuff here
}
function handleMouseMove(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#movelog").html("Move: "+ mouseX + " / " + mouseY);
// Put your mousemove stuff here
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
}); // end $(function(){});
</script>
</head>
<body>
<p>Move, press and release the mouse</p>
<p id="downlog">Down</p>
<p id="movelog">Move</p>
<p id="uplog">Up</p>
<p id="outlog">Out</p>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
在画布事件上计算正确的鼠标单击或鼠标移动位置的最简单方法是使用这个小等式:
canvas.addEventListener('click', event =>
{
let bound = canvas.getBoundingClientRect();
let x = event.clientX - bound.left - canvas.clientLeft;
let y = event.clientY - bound.top - canvas.clientTop;
context.fillRect(x, y, 16, 16);
});
Run Code Online (Sandbox Code Playgroud)
如果画布有padding-left或padding-top,请通过以下方式减去 x 和 y :
x -= parseFloat(style['padding-left'].replace('px'));
y -= parseFloat(style['padding-top'].replace('px'));
| 归档时间: |
|
| 查看次数: |
111676 次 |
| 最近记录: |