Firefox 中的 event.offsetX [英] event.offsetX in Firefox

查看:24
本文介绍了Firefox 中的 event.offsetX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><头><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>在此处插入标题</title><脚本语言="javascript">函数主(){var canvas = document.getElementById("canvas");canvas.addEventListener("mousemove", function(e){if (!e) e = window.event;var ctx = canvas.getContext("2d");var x = e.offsetX;var y = e.offsetY;ctx.fillRect(x, y, 1, 1);});}<body onload="main();"><div style="width: 800px; height: 600px; -webkit-transform: scale(0.75,0.75); -moz-transform: scale(0.75,0.75)"><canvas id="canvas" width="400px" height="400px" style="background-color: #cccccc;"></canvas>

请考虑上面这个又快又脏的例子.请注意,我的画布包含在应用了缩放变换的 div 中.上面的代码在任何基于 webkit 的浏览器上都能完美运行.移动鼠标时,它会在画布上绘制点.不幸的是,它不在 Firefox 中,因为它的事件模型不支持 offsetX/Y 属性.考虑到画布位置、变换等,如何将鼠标坐标从(也许) event.clientX(Firefox 也支持)转换为画布相对坐标?谢谢,卢卡.

解决方案

试试layerX,layerY

var x = (e.offsetX === undefined) ?e.layerX : e.offsetX;var y = (e.offsetY === 未定义) ?e.layerY : e.offsetY;

FIDDLE

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script language="javascript">
function main(){
    var canvas = document.getElementById("canvas");
    canvas.addEventListener("mousemove", function(e){
        if (!e) e = window.event;
        var ctx = canvas.getContext("2d");

        var x = e.offsetX;
        var y = e.offsetY;

        ctx.fillRect(x, y, 1, 1);
    });
}
</script>
</head>
<body onload="main();">
<div style="width: 800px; height: 600px; -webkit-transform: scale(0.75,0.75); -moz-transform: scale(0.75,0.75)">
    <canvas id="canvas" width="400px" height="400px" style="background-color: #cccccc;"></canvas>
</div>
</body>
</html>

Please consider the above quick and dirty example. Please notice that my canvas is contained by a div having a scale transform applied. The above code works perfectly on any webkit based browser. While moving the mouse it draws points on the canvas. Unfortunately it doesn't in Firefox as its event model does not support the offsetX / Y properties. How can I transform mouse coordinates from (perhaps) event.clientX (which is supported in firefox too) into canvas relative coordinates taking into account canvas position, transform etc? Thanks, Luca.

解决方案

Try layerX, layerY

var x = (e.offsetX === undefined) ? e.layerX : e.offsetX;
var y = (e.offsetY === undefined) ? e.layerY : e.offsetY;

FIDDLE

这篇关于Firefox 中的 event.offsetX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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