Blobinabottle
Blobinabottle

Reputation: 15

How to use keyboards event while editing text in fabricjs

Is there a way to listen to key events while you are editing a text? (in itext or textbox or whatever). Our goal is to be able to hit cmd-b or cmd-i to set the selected part of your text in bold or italic.

Thanks for your help!

Upvotes: 0

Views: 848

Answers (1)

Durga
Durga

Reputation: 15604

DEMO

window.addEventListener("keydown",onKeyDown);
function onKeyDown(e){
 if (event.which == 73 && event.ctrlKey ) {
    //ctrl+i
    makeItalic();
 }
 if (event.which == 66 && event.ctrlKey ) {
    //ctrl+b
    makeBold();
 }
}

var canvas = new fabric.Canvas('canvas');

var text = 'FabricJS Is Awsome';
var itext = new fabric.IText(text, {
    left: 100,
    top: 100,
    fontSize: 40,
    fill: '#000'
})
canvas.add(itext);
canvas.setActiveObject(itext);
function makeItalic(){
  itext.setSelectionStyles({fontStyle:'italic'});// set your property
  canvas.renderAll();
}
function makeBold(){
 itext.setSelectionStyles({fontWeight:'bold'});
 canvas.renderAll();
}
.canvas-wrappter {
    position: relative;
}
canvas {
    border: 1px solid #000;
}
.itext {
    width: 300px;
    background: transparent;
    position: absolute;
    z-index: 2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.16/fabric.min.js"></script>
<div class="canvas-wrapper">
    <canvas id="canvas" width="500" height="500"></canvas>
</div>

setSelectionStyles(style) use this function to set your style.

Upvotes: 1

Related Questions