Reputation: 1401
I am using Fabric.js to implement a application that will allow users to select a image template and then write some text over the image and then export the image. I tried an preliminary implementation. The problem I had is that after making the image appear in the canvas the image disappears after I click the image.
This is the javascript:
$(document).ready(function(){
console.log("entering the ad_man js file");
canvas = new fabric.Canvas('c');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
};
img.src = 'http://ovtoaster.com/wp-content/uploads/2014/02/cc-logo.jpg';
var textCharsInfo = function (textObj) {
var results = { charDims: [], totalLength : 0 };
if (textObj && textObj.text && textObj.text.length > 0) {
var str = '';
var prevWidth = 0;
for (var i = 0, length = textObj.text.length; i < length; i++) {
var c = textObj.text.charAt(i);
str += c;
var txtObjForCalc = new fabric.IText(str, {
fontFamily: textObj.fontFamily,
fontWeight: textObj.fontWeight,
fontSize: textObj.fontSize,
left: 2000,
top: 2000,
useNative: true
});
canvas.add(txtObjForCalc).renderAll();
var charWidth = txtObjForCalc.width - prevWidth;
prevWidth = txtObjForCalc.width;
results.charDims.push({ width: charWidth, height: txtObjForCalc.height });
canvas.remove(txtObjForCalc);
txtObjForCalc = null;
}
results.totalLength = prevWidth;
}
return results;
};
var text = new fabric.IText("This is text that is curved along an arc.", {
fontFamily: 'Italianno',
fontWeight: '',
fontSize: 40,
left: 250,
top: 250,
useNative: true
});
canvas.add(text);
canvas.renderAll();;
});
This the html part:
<h1>Hello World test</h1>
<canvas id="c" width="400" height="400">test</canvas>
<img src="http://ovtoaster.com/wp-content/uploads/2014/02/cc-logo.jpg" id="image_man"></img>
Here is the JSFiddle. How do I retain the image?
Here is an updated version of the fiddle with more changes. I was able make the initial picture work the way I want. Now on changing the background image on click make the new image vanish as well. Here is a jsfiddle.
Upvotes: 1
Views: 2084
Reputation: 6351
Problem is you are adding the image into canvas in native style, when you used this style the image object is not added to fabric canvas, When you clicked on drawn text, the fabric redraws all shapes which are added to canvas, so unadded image would be disappear.
Add image this way into canvas
var imgInstance = new fabric.Image(img);
canvas.add(imgInstance);
Instead of native style
ctx.drawImage(img,0,0);
Upvotes: 1