Write Custom Text on Image Canvas with Fabric.Js and HTML5

Write custom text on image canvas with fabric.js and HTML5

You can use IText like this:

canvas.add(new fabric.IText('Tap and Type', {
fontFamily: 'arial black',
left: 100,
top: 100,
}));

And the full code:

var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change", function (e) { var file = e.target.files[0]; var reader = new FileReader(); console.log("reader " + reader); reader.onload = function (f) { var data = f.target.result; fabric.Image.fromURL(data, function (img) { var oImg = img.set({left: 70, top: 100, width: 250, height: 200, angle: 0}).scale(0.9); canvas.add(oImg).renderAll(); canvas.setActiveObject(oImg); }); }; reader.readAsDataURL(file);});
$('#fill').change(function(){ var obj = canvas.getActiveObject();
if(obj){ // old api // obj.setFill($(this).val()); obj.set("fill", this.value); } canvas.renderAll();});
$('#font').change(function(){ var obj = canvas.getActiveObject(); if(obj){ // old api // obj.setFontFamily($(this).val()); obj.set("fontFamily", this.value); } canvas.renderAll();});
function addText() { var oText = new fabric.IText('Tap and Type', { left: 100, top: 100 , });
canvas.add(oText); oText.bringToFront(); canvas.setActiveObject(oText); $('#fill, #font').trigger('change');}
document.querySelector('#txt').onclick = function (e) { e.preventDefault(); canvas.deactivateAll().renderAll(); document.querySelector('#preview').src = canvas.toDataURL();};
canvas{  border: 1px solid black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.6/fabric.min.js"></script>
<input type="file" id="file"><input type="color" value="blue" id="fill" /><select id="font"> <option>arial</option> <option>tahoma</option> <option>times new roman</option></select><button onclick="addText()">Add Custom Text</button><br /><canvas id="canvas" width="750" height="550"></canvas><a href='' id='txt' target="_blank">Click Me!!</a><br /><img id="preview" />

Fabric.js layering text over Images on a Canvas

i added canvas.sendToBack(y); & canvas.sendToBack(textBox); into the function body , where you add the panel png & the textbox png, and it works. The i-text objects 'ChiefKeef' are above the pane image.

i 've made a jsfiddle with sample images because i could not reproduce yours, but you can see the result(by pressing the monkey :) ). http://jsfiddle.net/5KKQ2/495/

snippets:

x[i] = new
fabric.Image.fromURL("https://t2.ftcdn.net/jpg/00/97/16/03/500_F_97160389_tVczY4dIrtaRFkSMhV9elnU0NBMVJ1Y3.jpg", function(y){
//just add canvas.sendToBack(y);
canvas.add(y);canvas.sendToBack(y);
}, {
top: (5+(65*topShift)),
left: leftShift,
height:65,
width:195,
borderColor: "blue",
hasControls: true,
lockMovementX: true,
lockMovementY: true
});
var textBox = new fabric.Image.fromURL("https://t2.ftcdn.net/jpg/00/90/00/97/500_F_90009771_mWttXqopbyZZMVcyuXd5y2iQeeDK9NJm.jpg", function(textBox){
//just add canvas.sendToBack(textBox);
canvas.add(textBox);canvas.sendToBack(textBox);
}, {
top: 200,
left: 5,
height:50,
width:300,
borderColor: "blue",
hasControls: false,
lockMovementX: true,
lockMovementY: true
});

hope helps, good luck.

Fabric.js not writing text on html5 canvas

i tried and i got my answer this way. this is my code:

  $('#addText').click(function () {
changetext();

});

function changetext(){

var color = document.getElementById('color').value;
var mytext = document.getElementById('mytext').value;
var textObj = new fabric.Text(mytext, {

fontFamily: 'Arial',
fontSize:30,
left:10,
top:10,
fill:color,
shadow: 'green -5px -5px 3px',

});
canvas.add(textObj);
canvas.renderAll();
};

$('.toggleWidth').click(function(e) {
e.preventDefault();
var id = $(this).attr("href");
$(id).toggle();
});

jQuery.fn.extend({
slideRight: function() {
return this.each(function() {
$(this).animate({
width: 'show'
});
});
},
slideLeft: function() {
return this.each(function() {
$(this).animate({
width: 'hide'
});
});
},
slideToggleWidth: function() {
return this.each(function() {
var h = $(this);
if (h.css('display') == 'none') {
h.slideRight();
} else {
h.slideLeft();
}
});
}
});
});

Add remove icon on image in canvas HTML5 and Fabric js

You'll need to draw icon image using selected object's coordinates and it's width and height, rather than having it attached to objects transformation point. If you do su, you'll lost resizing functionality for that transformation point. Also, after object's rotation it will be hard to tell which transformation point is closest to upper right corner. I would preffer to have some exterlal toolbar button, that will do this, or have context menu with it.

add a button, or some other element

<button id="remove" style="display:none">remove</button>

and add this to your code

$('#remove').on('click', function(){
canvas.getActiveObject().remove();
});

canvas.on('object:selected', function(o) {
if (o.target.isType('image')) {
$('#remove').show();
}
});

canvas.on('selection:cleared', function() {
$('#remove').hide();
});

canvas text is not drawn on an image

Remove addText from onclick, and add to addImage

function addImage(url) {
fabric.Image.fromURL(url, function (oImg) {
oImg.selectable = false;
canvas.add(oImg);
addText('Hello World');
});
};

Example

Draw text on canvas using fabric.js

Also be aware that you need to actually have loaded a cufon font. There is no default font when using Fabric.js.

<script src="fabric.js"></script>
<script src="cufon.calibri.js"></script>

There are so many fonts available from http://www.cufonfonts.com/

This being the case the author is planning on removing the need for cufon. Discussed here: Fabric.js + Google Fonts

If you're wanting to render a block, then some text inside of that block. I would do something like this.

//Render the block
var block = canvas.add(new fabric.Rect({
left: 100,
top: 100,
fill: 'blue'
}));

//Render the text after the block (so that it is in front of the block)
var text = canvas.add(new fabric.Text('I love fabricjs', {
left: block.left, //Take the block's position
top: block.top,
fill: 'white'
}));

//Render the text and block on the canvas
//This is to get the width and height of the text element
canvas.renderAll();

//Set the block to be the same width and height as the text with a bit of padding
block.set({ width: text.width + 15, height: text.height + 10 });

//Update the canvas to see the text and block positioned together,
//with the text neatly fitting inside the block
canvas.renderAll();

BitmapText using fabricjs

Here you can see a basic override of the Textbox class.

I added all the properties i needed to handle the basic functionality, i stubbed the measureChar function to return the fixed width of the bitmap font, 6px.

At initialize time i create a map that tells me the position of the most common chars in the bitmap font, and finally i wrote a simple render method that retrieve the part of the canvas it needs in order to draw that character.

You still need to figure out fontColor, fontSize, doubleWidth and doubleHeight, but should be straight forward now that you have this example

(function() {  fabric.BitmapText = fabric.util.createClass(fabric.Textbox, {    type: 'bitmapText',    bitmap: 'https://i.stack.imgur.com/ITDgw.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: 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 }; },
_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); }); }, });

var canvas = new fabric.Canvas('c'); var text = new fabric.BitmapText('Hello i am a bitmap text');
canvas.add(text); canvas.setActiveObject(text);})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.1.0/fabric.min.js"></script><canvas id="c" width="350" height="400" />


Related Topics



Leave a reply



Submit