anonymoose
anonymoose

Reputation: 1243

How to use Google Fonts to manipulate text on a fabricjs canvas?

I'd like to be able to designated a few google fonts as buttons to change text on a canvas. I was able to write something to change between a few basic fonts but after a few hours tinkering with Google Fonts haven't been able to get it to work.

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>

Upvotes: 2

Views: 631

Answers (1)

andreas
andreas

Reputation: 16936

Your Javascript code is totally correct, except You simply forgot to set your active Object after adding it to the canvas:

canvas.setActiveObject(text)

Otherwise fabric doesn't know, what your active object is and cannot access its properties.

Also you included a CSS file with a <script> tag, which throws the script error on the console. Always make sure, your markup is valid.

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();
});
canvas {
  border: 1px solid #dddddd;
  border-radius: 4px;
  margin: 10px 0px 0px 12px;
}
<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>

Upvotes: 3

Related Questions