Tento výukový program byl vytvořen pro otázku StackOverflow, kde uživatel potřeboval vytvořit textový objekt v Fabric.js, který pracuje s bitmapami namísto písem. Příklad kódu obsahuje vše, co potřebujete vědět pro spuštění podtřídy. Zvažte, že podtřídění je jakousi poslední možností, když nemůžete získat potřebnou funkcionalitu s jinými API (události, vlastní ovládací prvky).
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);