In an app I'm building I'm using fabricjs to render text onto a canvas. I want to use a button to make that text bold but there seems to be a problem with how it gets rendered. Instead of it happening asynchronously or at the same time, I have to click outside the selected text before anything happens. I don't really know how to explain it too well, so I reproduced the challenge I'm having in a CodePen.
https://codepen.io/JojoDuke/pen/wvrgjaw
Code
//HTML
<canvas id="canvas" width="600" height="100"></canvas>
<button id="boldBtn">Make Bold</button>
<button id="normalBtn">Make Normal</button>
//Script
const boldBtn = document.getElementById('boldBtn');
const normalBtn = document.getElementById('normalBtn');
const canvas = new fabric.Canvas('canvas', {
backgroundColor: 'grey',
});
const text = new fabric.IText('Type text here', {
left: 100,
top: 10,
});
canvas.add(text);
canvas.renderAll();
boldBtn.addEventListener('click', async () => {
text.fontWeight = await "bold";
})
normalBtn.addEventListener('click', async () => {
text.fontWeight = await "normal";
})
Like the method is async canvas wait an event on it to take into consideration the element modification
one way is to force the refresh of the text in the canvas
to do it you can :
canvas.renderAll()canvas.add(text)all these methods should be place after you update the element attribute
boldBtn.addEventListener('click', async () => {
text.fontWeight = await "bold";
canvas.add(text);
})
normalBtn.addEventListener('click', async () => {
text.fontWeight = await "normal";
canvas.add(text);
})
As Jeremy mentioned you can add the element to the canvas during the asycronous event or force the canvas to do a re-render of all elements contained within.
Example:
boldBtn.addEventListener('click', async () => {
text.fontWeight = await "bold";
canvas.renderAll();
})
normalBtn.addEventListener('click', async () => {
text.fontWeight = await "normal";
canvas.renderAll();
})
Working codepen: https://codepen.io/carve-the-looper/pen/VwMbxpX