2017-10-29 88 views
0

我有兩個函數,每個都繪製文本,但我希望無論哪個函數被點擊來取代當前繪製的一個(以便一次只繪製一個)。我該如何做到這一點?提前致謝。替換fabricjs畫布上的函數(文本)?

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>

+0

你現在已經解決了你的問題嗎? – eeya

+0

不,我還沒有 –

回答

1

你可以叫你給canvas元素上clear方法,使您給出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

希望這有助於你的情況。

+0

謝謝,這很有幫助!如果我想讓其他功能持續存在,例如其他文本,我會如何讓它保留下來? [這是一個帶有第三個函數的JSFiddle](http://jsfiddle.net/code4ever/9t3gn533/2/)。如果您願意,我還可以創建一個新問題。再次感謝! –

+0

你想有一個'給定的文字圖紙'保留在同一個'canvas'元素上嗎? – eeya

+0

是的,這可能嗎? –

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(); 
 
}
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>

您可以設置文本的文本對象隨文字屬性或使用setText()