Reputation: 1243
I have two functions that each draw text but I'd like whichever function is clicked to replace the currently drawn one (so that there is only one drawn at a time). How might I accomplish this? Thanks in advance.
var $ = function(id) {
return document.getElementById(id)
};
var canvas = this.__canvas = new fabric.Canvas('c');
canvas.setHeight(300);
canvas.setWidth(500);
function textOne() {
canvas.add(new fabric.IText('One', {
left: 50,
top: 100,
fontFamily: 'arial',
fill: '#333',
fontSize: 50
}));
}
function textTwo() {
canvas.add(new fabric.IText('Two', {
left: 200,
top: 100,
fontFamily: 'arial black',
fill: '#333',
fontSize: 50
}));
}
canvas {
border: 1px solid #dddddd;
border-radius: 3px;
margin-top: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<button onclick="textOne()">One</button>
<button onclick="textTwo()">Two</button>
<canvas id="c"></canvas>
Upvotes: 0
Views: 446
Reputation: 15614
var canvas = new fabric.Canvas('c');
canvas.setHeight(300);
canvas.setWidth(500);
var text = new fabric.IText('One', {
left: 50,
top: 100,
fontFamily: 'arial',
fill: '#333',
fontSize: 50
});
canvas.add(text);
function replaceText(val) {
text.setText(val);
canvas.renderAll();
}
canvas {
border: 1px solid #dddddd;
border-radius: 3px;
margin-top: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.9/fabric.js"></script>
<button onclick="replaceText('One')">One</button>
<button onclick="replaceText('Two')">Two</button>
<canvas id="c"></canvas>
You can set text to text object with text property or use setText()
.
Upvotes: 0
Reputation: 1171
You can call the clear
method on your given canvas
element so that your given canvas
context can clear the contents inside in your current text drawings
JS Code:
var $ = function(id) {
return document.getElementById(id)
};
var canvas = this.__canvas = new fabric.Canvas('c');
canvas.setHeight(300);
canvas.setWidth(500);
function textOne() {
canvas.clear(); // Clear the given canvas
canvas.add(new fabric.IText('One', {
left: 50,
top: 100,
fontFamily: 'arial',
fill: '#333',
fontSize: 50
}));
}
function textTwo() {
canvas.clear(); // Clear the given canvas
canvas.add(new fabric.IText('Two', {
left: 200,
top: 100,
fontFamily: 'arial black',
fill: '#333',
fontSize: 50
}));
}
Here's a JS Fiddle for a given example: http://jsfiddle.net/7me0eat3
Hope this helps for your case.
Upvotes: 1