如何在fabricjs中编辑文本时使用键盘事件

时间:2017-07-14 14:31:44

标签: fabricjs

在编辑文本时,有没有办法收听关键事件? (在itext或textbox或其他)。我们的目标是能够点击cmd-b或cmd-i以粗体或斜体设置文本的选定部分。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

<强>样本

&#13;
&#13;
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();
}
&#13;
.canvas-wrappter {
    position: relative;
}
canvas {
    border: 1px solid #000;
}
.itext {
    width: 300px;
    background: transparent;
    position: absolute;
    z-index: 2;
}
&#13;
<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>
&#13;
&#13;
&#13;

setSelectionStyles(style)使用此功能设置您的风格。