我希望能够将一些谷歌字体指定为按钮来更改画布上的文本。我能够在一些基本字体之间写一些东西,但几个小时之后,谷歌字体的修补工作无法让它发挥作用。
canvas = new fabric.Canvas('c');
var text = new fabric.Text("Some Text", {
fontFamily: 'helvetica neue',
fill: '#000',
fontSize: 60
});
canvas.add(text);
document.getElementById('times').addEventListener('click', function(e) {
canvas.getActiveObject().set("fontFamily", "times");
canvas.renderAll();
});
document.getElementById('tangerine').addEventListener('click', function(e) {
canvas.getActiveObject().set("fontFamily", "tangerine");
canvas.renderAll();
});
canvas {
border: 1px solid #dddddd;
border-radius: 4px;
margin: 10px 0px 0px 12px;
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<script type="text/javascript" src="https://fonts.googleapis.com/css?family=Tangerine" rel="stylesheet"></script>
<canvas id="c" width="400" height="400"></canvas>
<br>
<button id="times">Times</button>
<button id="tangerine">Tangerine</button>
答案 0 :(得分:1)
你的Javascript代码是完全正确的,除了你只是忘了在将它添加到画布后设置你的活动对象:
canvas.setActiveObject(text)
否则,Fabric不知道您的活动对象是什么,无法访问其属性。
此外,您还包含一个带有<script>
标记的CSS文件,该文件会在控制台上引发脚本错误。始终确保您的标记有效。
var canvas = new fabric.Canvas('c');
var text = new fabric.Text("Some Text", {
fontFamily: 'helvetica neue',
fill: '#000',
fontSize: 60
});
canvas.add(text);
canvas.setActiveObject(text) // <-- see this
document.getElementById('times').addEventListener('click', function(e) {
canvas.getActiveObject().set("fontFamily", "times");
canvas.renderAll();
});
document.getElementById('tangerine').addEventListener('click', function(e) {
canvas.getActiveObject().set("fontFamily", "tangerine");
canvas.renderAll();
});
&#13;
canvas {
border: 1px solid #dddddd;
border-radius: 4px;
margin: 10px 0px 0px 12px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Tangerine" rel="stylesheet" />
<canvas id="c" width="400" height="150"></canvas>
<br>
<button id="times">Times</button>
<button id="tangerine">Tangerine</button>
&#13;