使用HTML5、Phonegap和Android,鼠标点击(或触摸)画布会导致选择。

13

我正在使用easlejs+phonegap开发HTML5游戏,但是每次在画布上点击/触摸/mousedown时屏幕会闪烁。

下面是我为测试此问题而创建的非常简单的代码,以查看它是否与easlejs相关。从代码中可以看出,这与easlejs无关,只是一个html5/phonegap问题。

您可以看到我还尝试了no select CSS样式,但没有成功。

截图显示当在画布上按住鼠标时出现橙色边框(第一张图片),然后释放鼠标(第二张图片)

<!doctype html>
<html>
<head>
    <title></title>
    <style type="text/css">
        #canvas
        {
            user-select: none;
            -webkit-user-select: none;
            -moz-user-select: none;
        }
    </style>
</head>
<body>
    <canvas  id="canvas" width="320" height="480"></canvas>
    <script type="text/javascript">
        var canvas = document.getElementById("canvas");

        canvas.addEventListener("mousedown", function(e)
        {
            var ctx = canvas.getContext("2d");
            var x = Math.random() * 320;
            var y = Math.random() * 480;
            var w = Math.random() * 100;
            var h = Math.random() * 100;

            ctx.fillStyle = "#FF0000";

            ctx.fillRect(x,y,w,h);
        }, false);
    </script>
</body>
</html>

也许可以这样做:document.addEventListener("selectstart", function(){ return false; }); 对于dragstart事件也是同样的处理... - Zevan
不幸的是,那并没有帮助。甚至尝试在画布上添加事件也不行。 - Gautam
2个回答

18

编辑:结果发现EaselJS仍然存在触摸显示选择的错误。 为了解决这个问题,我在阅读了这篇文章后向画布添加了一个CSS属性:https://stackoverflow.com/a/7981302/66044

修复方法如下: -webkit-tap-highlight-color: transparent;


通过参考这篇文章:Prevent page scroll on drag in IOS and Android,我成功地解决了这个问题。

以下是可用的代码。 修复是处理touchstart/end事件以处理点击。 不再出现橙色选择状态。

在2.2模拟器和我的设备(运行Cyanogenmod ICS的Samsung Captivate)中进行了测试。

<!doctype html>
<html>
<head>
    <title></title>
</head>
<body>
    <canvas  id="canvas" width="320" height="480"></canvas>
    <script type="text/javascript" src="cordova-1.7.0.js"></script>
    <script type="text/javascript">
        var canvas = document.getElementById("canvas");

        // FIX: Cancel touch end event and handle click via touchstart
        document.addEventListener("touchend", function(e) { e.preventDefault(); }, false);
        canvas.addEventListener("touchstart", function(e)
        {
            var ctx = canvas.getContext("2d");
            var x = Math.random() * 320;
            var y = Math.random() * 480;
            var w = Math.random() * 100;
            var h = Math.random() * 100;

            ctx.fillStyle = "#FF0000";

            ctx.fillRect(x,y,w,h);

            // FIX: Cancel the event
            e.preventDefault();
        }, false);
    </script>
</body>
</html>

谢谢!我只需要CSS部分,但是我无法相信有多难找到其他人也遇到了在移动站点上每次触摸活动按钮时闪烁的问题。这非常令人分心,对于我的访问者来说并没有视觉上的帮助,因为我已经为他们提供了足够的即时、视觉反馈,而不需要“闪烁”... - exoboy

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接