【问题标题】:Phonegap canvas touch eventsPhonegap 画布触摸事件
【发布时间】:2018-03-20 18:25:35
【问题描述】:

我在尝试使用触摸事件在画布元素上绘图时遇到了一点问题。发生的事情是我恢复了 pageX 和 pageY 但它们似乎不正确。正如你在图片中看到的,我点击了红点所在的位置,但坐标是黑色矩形所在的位置。

IMAGE

我提供的代码不是我的,我已经做了一些代码,但问题是一样的,我在联想 Tab3 7、小米 Mi5 和三星 S8 上尝试过,结果总是一样的。

那么请谁能帮我解决这个问题?

[编辑]当我从上到下触摸时,黑色指针离触摸点更远,然后我这样做到顶部它到达触摸点。

var can, ctx, canX, canY, mouseIsDown = 0;



    function init() {

        can = document.getElementById("canvas");

        ctx = can.getContext("2d");



        can.addEventListener("mousedown", mouseDown, false);

        can.addEventListener("mousemove", mouseXY, false);

        can.addEventListener("touchstart", touchDown, false);

        can.addEventListener("touchmove", touchXY, true);

        can.addEventListener("touchend", touchUp, false);



        document.body.addEventListener("mouseup", mouseUp, false);

        document.body.addEventListener("touchcancel", touchUp, false);

    }



    function mouseUp() {

        mouseIsDown = 0;

        mouseXY();

    }



    function touchUp() {

        mouseIsDown = 0;

        // no touch to track, so just show state

        showPos();

    }



    function mouseDown() {

        mouseIsDown = 1;

        mouseXY();

    }



    function touchDown() {

        mouseIsDown = 1;

        touchXY();

    }



    function mouseXY(e) {

        if (!e)

            var e = event;

        canX = e.pageX - can.offsetLeft;

        canY = e.pageY - can.offsetTop;

        showPos();

    }



    function touchXY(e) {

        if (!e)

            var e = event;

        e.preventDefault();

        canX = e.targetTouches[0].pageX - can.offsetLeft;

        canY = e.targetTouches[0].pageY - can.offsetTop;

        showPos();

    }



    function showPos() {

        // large, centered, bright green text

        ctx.font = "24pt Helvetica";

        ctx.textAlign = "center";

        ctx.textBaseline = "middle";

        ctx.fillStyle = "rgb(64,255,64)";

        var str = canX + ", " + canY;

        if (mouseIsDown)

            str += " down";

        if (!mouseIsDown)

            str += " up";

        ctx.clearRect(0, 0, can.width, can.height);

        // draw text at center, max length to fit on canvas

        ctx.fillText(str, can.width / 2, can.height / 2, can.width - 10);

        // plot cursor

        ctx.fillStyle = "black";

        ctx.fillRect(canX -5, canY -5, 10, 10);

    }

【问题讨论】:

    标签: javascript cordova canvas draw phonegap


    【解决方案1】:

    已经找到了。

    真正的问题是我使用 CSS 设置宽度和高度。 有Width和Height属性需要填充。

    然后在触摸事件上执行此操作

    function funcName(e){
       let rect = canvas.getBoundingClientRect();
       context.fillRect(e.touches[0].pageX - rect.left, e.touches[0].pageY - rect.top, 10, 10);
    }
    

    希望我解决的问题对任何人都有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-28
      • 2014-03-07
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多