从一个画布到另一个画布绘制线条

时间:2015-09-01 13:57:07

标签: html5-canvas

我有多个画布,想在画布上的两个点之间绘制线条,其中一个点在一个画布上,另一个点在第二个(不同的)画布上。

如何用上述条件绘制线条?

ctx.beginPath();
ctx.moveTo(10,30);//point on canvas1
ctx.lineTo(100,70);//point on canvas2
ctx.stroke();

1 个答案:

答案 0 :(得分:0)

为此,请使用第二个画布的ctx.setTransform函数到第一个画布的

function matchCoordinateSpace(ctx1,ctx2){

    // get the window positions of both canvases
    var can1Loc = ctx1.canvas.getBoundingClientRect();
    var can2Loc = ctx2.canvas.getBoundingClientRect();

    // get the relative offset 
    var can2Rel = {
        x:can1Loc.left-can2loc.left,
        y:can1Loc.top-can2loc.top,
    };

    // set the transforms
    ctx2.setTransform(1,0,0,1,0,0); // just to make sure the first canvas coordinate space
                                    // is correctly set.

    ctx2.setTransform(1,0,0,1,can2Rel.x,can2Rel.y); // translates the canvas to the
                                                    // same coordinates as the firstChild

    // The second canvas now is in the same relative coordinate space as the first;
    // All drawing methods on the second canvas will be in the first canvas coordinate space.
    // You only need to do this once, or whenever the two canvases change relative position.

    return can2Rel;  // incase you need the offset

}


//ctx1 is the first canvas
//ctx2 is the second

var can2Offset = matchCoordinateSpace(ctx1,ctx2);


// You will have to draw the line on each canvas in turn                                               
ctx1.beginPath();  
ctx1.moveTo(10,30);
ctx1.lineTo(100,70);
ctx1.stroke();

ctx2.beginPath();   // this line will match up with the line drawn on the first.
ctx2.moveTo(10,30);
ctx2.lineTo(100,70);
ctx2.stroke();