使用jQuery在手机上手势捏缩放HTML5 Canvas

时间:2015-09-15 22:27:58

标签: javascript jquery html5 canvas

我想知道是否有人可以帮助我解决我在移动应用中遇到的缩放问题。

基本上,我正在使用HTML5画布(因为我希望以后能够在其上绘图)并且希望能够使用捏合手势放大画布的特定区域。还可以平移画布图像。

目前,我正在使用Hammer.js。

以下代码有效,但图像会跳转并且对缩放手势非常敏感。因为缩放与手势不成比例。

$(document).ready(function(e) {
    var canvas = document.getElementById('geomap');
    var context = canvas.getContext('2d');
    var imageObj = new Image();
    var mc = new Hammer.Manager(canvas);
    var pinch = new Hammer.Pinch();
    mc.add([pinch]);    // add to the Manager

    imageObj.src = './images/MapCanvas.png';

    var canvasHammer = {
        scale : 1,      // Scale of the image
        xLast : 0,      // Last location X on screen
        yLast : 0,      // Last location Y on screen
        xImage : 0,     // Last location X on image
        yImage : 0      // Last location Y on image
    };

    imageObj.onload = function() {
        context.drawImage(imageObj, 0, 0);
        context.scale(canvasHammer.scale, canvasHammer.scale);
    };

    // ============ GESTURE PINCH =================             
    mc.on("pinch", function(ev) {
        var zoomScale = ev.scale;

        var posX = ev.center.x;
        var posY = ev.center.y;

        // Find current location on screen
        var xScreen = posX;
        var yScreen = posY;

        canvasHammer.xImage = canvasHammer.xImage + ((xScreen - canvasHammer.xLast) / canvasHammer.scale);
        canvasHammer.yImage = canvasHammer.yImage + ((yScreen - canvasHammer.yLast) / canvasHammer.scale);

        canvasHammer.scale = zoomScale;

        // Determine the new location of the image
        var xNew = (xScreen - canvasHammer.xImage) / canvasHammer.scale;
        var yNew = (yScreen - canvasHammer.yImage) / canvasHammer.scale;

        canvasHammer.xLast = xScreen;
        canvasHammer.yLast = yScreen;

        context.clearRect(0, 0, canvas.width, canvas.height);   // Clear the contents of the canvas.
        //context.save();
        context.drawImage(imageObj,xNew,yNew);      
        context.scale(zoomScale,zoomScale);
        //context.restore();
        $('.stuff').html("<p> Pinch : " + zoomScale + "<br>xNew : " + xNew + "<br>yNew : " + yNew + "</p>"); // For diagnostics!

    });


    $('#syncbutton').click(function() {
        if(hasInternetConnection())
        {
            alert('Nothing to sync. All maps currently up-to-date.');
        }
        else
        {
            alert('You need an internet connection to sync.');  
        }

    });

});

HTML:

<div data-role="page" id="map_editor" data-theme="b">
            <div data-role="header">
                <h1>Map Editor</h1>
            </div>
            <div data-role="content" class="pwdcontent">    
                <div class="mapcontainer">
                    <canvas id="geomap" class="mapCanvas"></canvas>
                    <div class="stuff"></div>   

                </div>


            </div>
        </div>

谢谢!

0 个答案:

没有答案