将fabric.js对象与IText元素的内部文本的左上角对齐

时间:2015-10-19 16:27:11

标签: javascript canvas fabricjs

http://jsfiddle.net/541ev5nh/15/

我正在尝试将红色Text对象与黑色IText对象的左上角对齐。当Itext对象未旋转时(角度为0),您可以看到文本已正确对齐。但是,旋转IText会关闭对齐。

调整或更改IText的文本也会导致对齐,但暂时不要担心。轮换是目前唯一需要解决的问题。

问题显然来自于我使用魔术数字来对齐这两个项目。我需要一种公式化的方法来导出这些数字,以便在旋转IText时保持对齐一致。有什么想法吗?

HTML:

<canvas id="canvas" width="800" height="600" style=""></canvas>

使用Javascript:

var w = 800;
var h = 600;
var cx = w/2;
var cy = h/2;

var auto = false; // auto/manual rotation

// Main "Text"
var txt = "Text";
var canvas = new fabric.Canvas('canvas');
var text = new fabric.IText(txt, { 
    left: 20, 
    top: 30, 
    fontFamily: 'sans-serif',
    fontSize: 80
});
canvas.add(text);
var pt = new fabric.Point(cx,cy);
text.setPositionByOrigin(pt, 'center', 'center');
canvas.setActiveObject(text);


// decorator
var txt = "Top left";
var deco = new fabric.Text(txt, { 
    left: 20, 
    top: 30, 
    fontFamily: 'sans-serif',
    fontSize: 14,
    stroke: '#DD0000',
    fill: '#DD0000'
});
canvas.add(deco);


canvas.on('object:modified', onModified);

function onModified(data){
    var rotatedPoint = data.target.getPointByOrigin("left", "top");
    deco.rotate(data.target.angle);
    deco.setPositionByOrigin(new fabric.Point(rotatedPoint.x + 1, rotatedPoint.y + 11), 'left', 'top');
    canvas.renderAll();
}

var angle = -2;

if (auto){
    setInterval(onInterval, 30);
}
else{
    onInterval();
    text.setCoords();
}

function onInterval(){
    angle += 2;
    text.rotate(angle);
    var data = {
        target: text
    };
    onModified (data);
}

1 个答案:

答案 0 :(得分:0)

您可以通过制作对象组来实现这一目标。 Fabric对对象组有很好的支持 请参见此处:

// Main "Text"
    var txt = "Text";
    var canvas = new fabric.Canvas('canvas');
    canvas.clear();
    var text = new fabric.IText(txt, {     
        fontFamily: 'sans-serif',
        fontSize: 80
    });
    // decorator
    var txt = "Top left";
    var deco = new fabric.Text(txt, {  
        top:10,
        fontFamily: 'sans-serif',
        fontSize: 14,
        stroke: '#DD0000',
        fill: '#DD0000'
    });

    var group = new fabric.Group([ text, deco ], {  
      angle: 0
    });

    var lefts=canvas.getWidth()/2-group.getWidth()/2;
    var tops=canvas.getHeight()/2-group.getHeight()/2;
      group.set({
        'left':lefts,
        'top':tops
      });
    canvas.add(group);
    canvas.renderAll();

See in Fiddler