当我同时在另一个画布中拖动另一个图像时如何移动图像

时间:2015-03-03 00:39:19

标签: javascript jquery canvas html5-canvas fabricjs

我正在使用fabric.js来处理两幅画布。我还设置了两个画布来比较同一页面中的两个图像。

像这样:

<canvas id="firstImg" width="843" height="1200"></canvas> <canvas id="secondImg" width="843" height="1200"></canvas>

我想在另一个画布中拖动另一个图像时移动图像。

我的意思是当我拖动图像来改变firstImg画布中的位置时,我也同时在secondImg画布中移动另一个图像。

有可能吗?

1 个答案:

答案 0 :(得分:1)

你在找这样的东西吗?

我做了一个简单的功能,可以在canavs上绘制图像。拖动图像时,只需为两个画布调用该函数。

http://jsfiddle.net/Niddro/96rdnv3L/

&#13;
&#13;
var canvasOne = document.getElementById("canvasOne");
var ctxOne = canvasOne.getContext("2d");

var canvasTwo = document.getElementById("canvasTwo");
var ctxTwo = canvasTwo.getContext("2d");

var mouseX=0;
var mouseY=0;
var imageX=0;
var imageY=0;
var drag = false;
canvasOne.addEventListener("mousedown", function(){drag=true;}, false);
canvasOne.addEventListener("mouseup",  function(){drag=false;}, false);
canvasOne.addEventListener("mousemove", moveImage, false);

var myImage = new Image();
myImage.src = "http://home.niddro.com/HTML5/flxprt/img/logo_orange_small.png";

function moveImage(event) {
    if (drag) {
        var x = new Number();
        var y = new Number();
        var canvas = document.getElementById("canvasOne");
    
        if (event.x != undefined && event.y != undefined)
        {
          x = event.x;
          y = event.y;
        }
        else // Firefox method to get the position
        {
          x = event.clientX + document.body.scrollLeft +
              document.documentElement.scrollLeft;
          y = event.clientY + document.body.scrollTop +
              document.documentElement.scrollTop;
        }
    
        x -= canvas.offsetLeft;
        y -= canvas.offsetTop;
        var deltaX = mouseX-x;
        var deltaY = mouseY-y;
        drawImage(imageX-deltaX,imageY-deltaY,ctxOne,canvasOne,myImage);
        drawImage(imageX-deltaX,imageY-deltaY,ctxTwo,canvasTwo,myImage);
        
    }
}

drawImage(imageX,imageY,ctxOne,canvasOne,myImage);
drawImage(imageX,imageY,ctxTwo,canvasTwo,myImage);


function drawImage(x,y,ctx,canvas,img) {
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.drawImage(img,x,y);
}
&#13;
canvas {
    border: 1px solid black;
}
&#13;
<canvas id="canvasOne" width="500" height="300"></canvas><br />
<canvas id="canvasTwo" width="500" height="300"></canvas>
&#13;
&#13;
&#13;