Q:

Aligning Text Left, Center, and Right with fabricjs

I've got some text on my canvas and I'm trying to use buttons to align the text to the left, center, and right in it's  my fabricjs canvas. I saw this example but would prefer to use buttons over a select box. I've tried a bunch and am feeling pretty lost. 

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>

A:

The issue is not in the fabric code. Rather it was because you were using the same id for all the buttons. document.getElementById returns only the first instance and therefore your click listener was getting added to the 'left' button only

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>

