我有两个函数,每个函数都绘制文本,但我喜欢点击任何一个函数来替换当前绘制的函数(这样一次只绘制一个)。我怎么能做到这一点?提前谢谢。
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>
&#13;
答案 0 :(得分:1)
您可以在给定的clear
元素上调用canvas
方法,以便您的canvas
上下文可以清除current text drawings
JS代码:
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
}));
}
以下是给定示例的JS小提琴:http://jsfiddle.net/7me0eat3
希望这有助于您的情况。
答案 1 :(得分:0)
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();
}
&#13;
canvas {
border: 1px solid #dddddd;
border-radius: 3px;
margin-top: 5px;
}
&#13;
<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>
&#13;
您可以使用text属性将文本设置为文本对象,也可以使用setText()
。