I'm using konvajs ( https://konvajs.org ) to create a web page where user can drag drop furniture images into a canvas with background image. User can then click a submit button, i call stage.toDataUrl() , store it in a textarea and save to database. Everything works fine except when i load the base 64 string, my background image is missing but all the other drag and drop images are there. Below is my code in detail. Please help..
var stage = new Konva.Stage({
container: 'container',
width: 800,
height: 600
});
var canvasBg = new Image();
canvasBg.src = 'mybackgroundimage.png'; // --->> this is the image that fails to be saved as image
canvasBg.onload = function() {
initStage(canvasBg);
}
function initStage(canvasBg){
var background = new Konva.Layer();
background.id('background');
var layer = new Konva.Layer();
layer.id('items');
stage.add(background);
stage.add(layer);
drawBackground(background, canvasBg);
var item = '';
$('#product_container').on('dragstart', (e) => {
item = {};
item.src = e.target.dataset.imgsrc;
item.alt = e.target.dataset.imgalt;
item.id = e.target.dataset.imgid;
item.qty = 1;
item.price = e.target.dataset.price;
});
var con = stage.container();
con.addEventListener('dragover', function(e) {
e.preventDefault(); // !important
});
con.addEventListener('drop', function(e) {
e.preventDefault();
stage.setPointersPositions(e);
var group = new Konva.Group({
draggable: true
});
Konva.Image.fromURL(item.src, function(image) {
image.addName(item.alt);
image.setAttr('src', item.src);
image.id(item.id);
var stagePos = stage.getPointerPosition();
var imgPos = {
x : stagePos.x - image.width()/2,
y : stagePos.y - image.height()/2,
};
image.position(imgPos);
var text = new Konva.Text({
x: imgPos.x,
y: imgPos.y + image.height() + 4,
width: image.width(),
height: 20,
align: 'center',
verticalAlign: 'middle',
fontFamily: 'Calibri',
fontSize: 14,
text: item.alt,
fill: 'black'
});
group.add(image);
group.add(text);
layer.add(group);
layer.draw();
});
});
}
function drawBackground(background, bgImage) {
var context = background.getContext();
context.drawImage(bgImage, 0, 0, bgImage.width, bgImage.height, 0, 0, cWidth, cHeight);
}
// When user submit the form, i store stage.toDataURL() in textarea
$("#frmCanvas").submit(function(){
$("#stageimage").val(stage.toDataURL());
return true;
});
Here is the screenshot
Before save https://i.stack.imgur.com/kywbH.png
After Save https://i.stack.imgur.com/yCpn5.png