Reputation: 95
I am trying replace images on the canvas after editing it. I need to maintain the width and height of the original image after replacing it, this is my code :
it replaces the image with the new image to the original height and width of the old image as expected. But if I make some changes to old image and then replace the image the changes are not applied.
I want all the changes made on the old image like its height width and angle to be applied to new image
canvas.loadFromJSON(JSON.parse(json_data), canvas.renderAll.bind(canvas), function(o, object) {
if (object.type == 'image') {
var current_width = object.width;
var current_height = object.height;
object.setSrc(url, function() {
// method#1
object.scaleToWidth(current_width);
object.scaleToHeight(current_height);
canvas.renderAll();
});
}
});
Upvotes: 3
Views: 1252
Reputation: 15604
obj.set({
width: current_width,
height: current_height
})
Just set width and height no need to use scaleToWidth
and scaleToHeight
.
DEMO
var canvas = new fabric.Canvas('canvas1');
fabric.Image.fromURL("https://picsum.photos/200/300?random", function(oImg) {
oImg.set({
left: 30,
top: 30
})
canvas.add(oImg);
});
function changeSrc() {
var json_data = canvas.toJSON();
canvas.loadFromJSON(json_data, canvas.renderAll.bind(canvas), function(o, object) {
if (object.type == 'image') {
var current_width = object.width;
var current_height = object.height;
object.setSrc("https://i.imgur.com/4yOoOzl.jpg", function(obj) {
obj.set({
width: current_width,
height: current_height
})
canvas.renderAll();
});
}
});
}
canvas {
border:1px dotted black;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<button onclick="changeSrc()">Change Src</button>
<canvas id="canvas1" width="400" height="400" style=""></canvas>
Upvotes: 3