我的画布上有一些文字,我正在尝试使用按钮将文本对齐到左边,中间和右边,这是我的fabricjs画布。我看到this example但更喜欢在选择框上使用按钮。我尝试了一堆,感觉很迷茫。
var $ = function(id){return document.getElementById(id)};
var canvas = this.__canvas = new fabric.Canvas('c');
canvas.setHeight(300);
canvas.setWidth(300);
document.getElementById('text-align').onclick = function() {
canvas.getActiveObject().setTextAlign(this.value);
canvas.renderAll();
};
var text = new fabric.IText('Some demo\nText', {
left: 10,
top: 10,
fontSize: 22,
hasBorders: true,
hasControls: true,
cornerStyle: 'circle',
lockRotation: true,
hasControls: true,
lockUniScaling: true,
hasRotatingPoint: false,
})
canvas.add(text);
canvas {
border: 1px solid #dddddd;
margin-top: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.min.js"></script>
<button id="text-align" value="left">Left</button>
<button id="text-align" value="center">Center</button>
<button id="text-align" value="right">Right</button>
<canvas id="c"></canvas>
答案 0 :(得分:1)
问题不在结构代码中。相反,这是因为你对所有按钮使用相同的id。 document.getElementById
仅返回第一个实例,因此您的点击侦听器仅添加到“左侧”按钮
var $ = function(id) {
return document.getElementById(id)
};
var canvas = this.__canvas = new fabric.Canvas('c');
canvas.setHeight(300);
canvas.setWidth(300);
document.querySelectorAll('.text-align').forEach(function(btn) {
btn.onclick = function() {
canvas.getActiveObject().setTextAlign(this.value);
canvas.renderAll();
};
})
var text = new fabric.IText('Some demo\nText', {
left: 10,
top: 10,
fontSize: 22,
hasBorders: true,
hasControls: true,
cornerStyle: 'circle',
lockRotation: true,
hasControls: true,
lockUniScaling: true,
hasRotatingPoint: false,
})
canvas.add(text);
canvas {
border: 1px solid #dddddd;
margin-top: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.min.js"></script>
<button class="text-align" value="left">Left</button>
<button class="text-align" value="center">Center</button>
<button class="text-align" value="right">Right</button>
<canvas id="c"></canvas>