Hướng dẫn này đã được tạo cho câu hỏi StackOverflow trong đó người dùng cần thực hiện một đối tượng văn bản trong Fabric.js hoạt động với bitmap thay vì phông chữ. Ví dụ về mã chứa mọi thứ bạn cần biết để bắt đầu một lớp con. Hãy coi rằng phân lớp là phương sách cuối cùng khi bạn không thể có được chức năng cần thiết bằng các API khác (sự kiện, điều khiển tùy chỉnh).
fabric.BitmapText = fabric.util.createClass(fabric.Textbox, {
// important! type has to be the same of the className, but with first letter lowercase.
type: 'bitmapText',
bitmap: '/article_assets/font.png',
readyToRender: false,
charWidth: 6,
charHeight: 9,
fontSize: 9,
charMap: ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}'
.split('').reduce(function(acc, char, index) {
acc[char] = index + 31;
return acc;
}, {}),
// initialize can only be of the kind function(options) or function(arg, options)
// no other signatures.
initialize: function(text, options) {
this.callSuper('initialize', text, options);
var image = fabric.document.createElement('img');
image.onload = (function() {
var canvas = fabric.document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
console.log(canvas.width)
canvas.getContext('2d').drawImage(image, 0, 0);
this.bitmapResource = canvas;
this.readyToRender = true;
this.dirty = true;
if (this.canvas) this.canvas.requestRenderAll();
}).bind(this);
image.src = this.bitmap;
},
// override: make it return a fixed box 6x9
_measureChar: function(_char, charStyle, previousChar, prevCharStyle) {
return { width: 6, kernedWidth: 6 };
},
// ovveride, just draw the bitmpa we have.
_renderChar: function(method, ctx, lineIndex, charIndex, _char, left, top) {
if (!this.readyToRender) return;
var charMap = this.charMap, res = this.bitmapResource;
_char.split('').forEach(function(singleChar) {
ctx.drawImage(res, charMap[singleChar] * 6, 0, 5, 9, left, top - 6, 5, 9);
ctx.translate(6, 0);
});
},
});
// in order for your subclass to work with loadFromJSON you have to define this Static
// methd `fromObject`.
fabric.BitmapText.fromObject = function(object, callback) {
return fabric.Object._fromObject('BitmapText', object, callback, 'text');
};
var canvas = new fabric.Canvas('c');
var text = new fabric.BitmapText('Hello i am a bitmap text');
canvas.add(text);