Why is the zIndex sequence of my objects not what I expected? - konvajs

How can I get a list of all objects with all params (x, y, width, etc.), including zIndex param on the stage after completing resizing? And how can I set an zIndex for each object when creating a stage?
I have this code, but setZIndex not working correctly. Images are not set correctly.
const oKonvaStage = new Konva.Stage({
container: 'dropzone'
});
const oKonvaLayer = new Konva.Layer();
oKonvaStage.add(oKonvaLayer);
const oKonvaImage1 = new Konva.Image({
x: 624,
y: 433,
width: 1920,
height: 1280
});
const oImage1 = new Image();
oImage1.onload = function() {
oKonvaImage1.image(oImage1);
oKonvaLayer.add(oKonvaImage1);
oKonvaImage1.setZIndex(2);
oKonvaLayer.draw();
};
oImage1.src = 'image1.jpg';
oKonvaImage1.on('transformend', function(e) {
UpdateAttrs();
});
const oKonvaImage2 = new Konva.Image({
x: 9,
y: 254,
width: 1024,
height: 1024
});
const oImage2 = new Image();
oImage2.onload = function() {
oKonvaImage2.image(oImage2);
oKonvaLayer.add(oKonvaImage2);
oKonvaImage2.setZIndex(0);
oKonvaLayer.draw();
};
oImage2.src = 'image2.jpg';
oKonvaImage2.on('transformend', function(e) {
UpdateAttrs();
});
const oKonvaImage3 = new Konva.Image({
x: -586,
y: -315,
width: 1920,
height: 1199
});
const oImage3 = new Image();
oImage3.onload = function() {
oKonvaImage3.image(oImage3);
oKonvaLayer.add(oKonvaImage3);
oKonvaImage3.setZIndex(1);
oKonvaLayer.draw();
};
oImage3.src = 'image3.jpg';
Image3 has index = 1 but is over Image2 which has index = 2.

First off, prompted by #lavrton's comment, you should add the konva.Images to the canvas as soon as you have instantiated them - not in the image onload event. The image objects are no overhead to the canvas, and you can then be sure of the initial z-index sequence. You may change the sequence after that, but at least you start with a known layout.
And as a general rule, you need to take care when using any commands inside the onload event of an image. Image loading is asynchronous - meaning it does not happen in the sequence you might anticipate when you write the code. A large image coming from a slow server will load more slowly than a small image from a quick server, but you cannot make any assumptions about the sequence. The ONLY way you can ensure the sequence is to have the load of the second image initiated from the onload event of the first, but this is generally going to give bad UX.
Back to the code you posted, the code in my snippet below would appear to work as you intended. I switched the ECMA2015 const to plain old vars, and removed the unnecessary on-transforms.
I also added some code to analyse the results, showing the hoped-for zIndex value and the achieved zIndex values.
Note that the zIndex value in Konva is relative to the parent container and not absolute.
So, for example, when I set zondex=999 I actually get a value of 4.
Summary:
avoid calling code for which sequence is critical in onload events.
do not expect to get exactly the zindex you ask for.
var div = $('#dropzone');
var oKonvaStage = new Konva.Stage({container: 'dropzone', width: div.width(), height: div.height()});
var indexWanted = [];
var oKonvaLayer = new Konva.Layer();
oKonvaStage.add(oKonvaLayer);
var oKonvaImage1 = new Konva.Image({
name: 'image-1',
x: 20,
y: 20,
width: 300,
height: 100
});
var oImage1 = new Image();
oImage1.onload = function() {
oKonvaLayer.add(oKonvaImage1);
oKonvaImage1.image(oImage1);
oKonvaImage1.setZIndex(2);
indexWanted[0] = 2;
oKonvaLayer.draw();
sayPos();
};
oImage1.src = 'https://dummyimage.com/300x100/666/fff.png?text=Image-1'
var oKonvaImage2 = new Konva.Image({
name: 'image-2',
x: 10,
y: 100,
width: 300,
height: 100
});
var oImage2 = new Image();
oImage2.onload = function() {
oKonvaImage2.image(oImage2);
oKonvaLayer.add(oKonvaImage2);
oKonvaImage2.setZIndex(0);
indexWanted[1] = 0;
oKonvaLayer.draw();
sayPos();
};
oImage2.src = 'https://dummyimage.com/300x100/333/fff.png?text=Image-2';
var oKonvaImage3 = new Konva.Image({
name: 'image-3',
x: 280,
y: 80,
width: 300,
height: 100
});
var oImage3 = new Image();
oImage3.onload = function() {
oKonvaImage3.image(oImage3);
oKonvaLayer.add(oKonvaImage3);
oKonvaImage3.setZIndex(999); // <<<< notice this is set to 99. Compare to console output !!
indexWanted[2] = 999;
oKonvaLayer.draw();
sayPos();
};
oImage3.src = 'https://dummyimage.com/300x100/ccc/fff.png?text=Image-3';
oKonvaLayer.draw();
oKonvaStage.draw();
var picCnt = 0, s= '', imgNo = 0;
function sayPos(){
picCnt = picCnt + 1;
if (picCnt === 3){
for (var i = 0; i < indexWanted.length; i = i + 1){
imgNo = i + 1;
s = s + '<br/>Image-' + imgNo + ' zindex wanted = ' + indexWanted[i] + ' actual zIndex=' + oKonvaLayer.findOne('.image-' + imgNo).getAbsoluteZIndex();
}
$('#info').html(s)
}
}
#info {
font-size: 10pt;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/konva/2.5.1/konva.min.js"></script>
<p id='info' >
</p>
<div id='dropzone' style="position: absolute; top: 90px; z-index: -1; display: inline-block; left: 0px; width: 600px; height: 400px; background-color: silver;"></div>

Related

What is the proper way how to fire event on start and finish of the complex drawing using KanvaJS?

I am drawing a complex graphic on canvas using KonvaJS library. Execution takes few seconds and I want to monitor progress on user screen, but I can't make work functions like:
layer.on('draw', () => {
console.log('Draw finished')
})
What is the proper way how to fire event on start and finish of the drawing using KanvaJS?
Here is a test code where console.log('Draw finished') is not executed
var stage = new Konva.Stage({
container: 'canvas-container', // id of HTML div container
width: 1000,
height: 500,
});
function drawGrid(){
let layerMPE = new Konva.Layer();
let pxMax = stage.width();
let pyMax = stage.height();
let res = 10;
for (let px=0; px < pxMax; px += res){
for (let py=0; py < pyMax; py += res){
let rect = new Konva.Rect({
x: px,
y: py,
width: res,
height: res,
fill: 'red'
});
layerMPE.add(rect);
}
}
stage.add(layerMPE);
layerMPE.draw();
layerMPE.on('draw', () => {
console.log('Draw finished')
});
}
drawGrid();

Konva converting stage toDataUrl() do not work in chrome browser,but work well in safari browser

I have Konva Stage with few layers, when I try convert to image all stage - result is OK in safari browser , when I try convert stage in chrome ,firefox etc. - result is failed. I think that toDataUrl() method does
not work well in chrome browser ,firefox browser etc except for safari browser
<button id="save" type="button">save</button>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;
function downloadURI(uri, name) {
var link = document.createElement('a');
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
function drawImage(imageObj) {
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
// darth vader
var darthVaderImg = new Konva.Image({
image: imageObj,
x: stage.getWidth() / 2 - 200 / 2,
y: stage.getHeight() / 2 - 137 / 2,
width: 200,
height: 137,
name: 'myimg',
draggable: true
});
// add cursor styling
darthVaderImg.on('mouseover', function () {
document.body.style.cursor = 'pointer';
});
darthVaderImg.on('mouseout', function () {
document.body.style.cursor = 'default';
});
layer.add(darthVaderImg);
stage.add(layer);
stage.on('click tap', function (e) {
// if click on empty area - remove all transformers
if (e.target === stage) {
stage.find('Transformer').destroy();
layer.draw();
return;
}
// do nothing if clicked NOT on our rectangles
if (!e.target.hasName('myimg')) {
return;
}
// remove old transformers
// TODO: we can skip it if current rect is already selected
stage.find('Transformer').destroy();
// create new transformer
var tr = new Konva.Transformer();
layer.add(tr);
tr.attachTo(e.target);
layer.draw();
})
document.getElementById('save').addEventListener(
'click',
function () {
var dataURL = stage.toDataURL({ pixelRatio: 3 });
downloadURI(dataURL, 'stage.png');
},
false
);
}
var imageObj = new Image();
imageObj.onload = function () {
drawImage(this);
};
imageObj.src = 'https://www.decanterchina.com/assets/images/article/550/136031_decanter-cava-tasting-1.jpg';
</script>
Any possible reasons or solutions ? Thanks!!
If you look into the console you will see a message:
Konva warning: Unable to get data URL. Failed to execute 'toDataURL'
on 'HTMLCanvasElement': Tainted canvases may not be exported.
You have CORS issue. Take a look here for solutions:
Tainted canvases may not be exported
https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image

Post image data instead of image url in fabric js

I have implemented the Drag n Drop image, now the issue is when i am converting canvas data as toSVG and send it to server it includes the image URL instead of image data.
When user upload the file then i am using below method:
//Add photo in canvas
document.getElementById('add_image').addEventListener('change', function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({
left: 0,
top: 0,
angle: 0,
border: '#000',
stroke: '#F0F0F0', //<-- set this
strokeWidth: 0, //<-- set this
fill: 'rgba(0,0,0,0)'
}).scale(0.2);
canvas.add(oImg).renderAll();
canvas.moveTo(oImg, z_index);
z_index = z_index + 1;
//var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({
format: 'png',
quality: 1
});
});
};
reader.readAsDataURL(file);
$(this).val('');
});
then it sends the data as below:
< image xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="data:image/gif;base64,..." x="-100" y="-100" style="stroke: rgb(240,240,240); stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); fill-opacity: 0; fill-rule: nonzero; opacity: 1;" width="200" height="200">
Here ... contains base64 data.
If image is uploaded using Drag n Drop then i am using below method:
var new_image = new fabric.Image(obj, {
width: obj.naturalWidth,
height: obj.naturalHeight,
scaleX: setImageWidth/obj.naturalWidth,
scaleY: setImageHeight/obj.naturalHeight,
// Set the center of the new object based on the event coordinates relative
// to the canvas container.
left: e.layerX,
top: e.layerY,
id: 'verified_image'
});
canvas.add(new_image);
canvas.renderAll();
which sends the data as below:
< image id="verified_image" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://localhost/lynkus/uploads/userprofile/verified_image.png" x="-256" y="-256" style="stroke: none; stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;" width="512" height="512">
So both type of image uploading is working fine but the issue is i am trying to generate the png file using above svg. So system is able to create png for 1st option but not for 2nd option as its have a URL.
So is there a way to send data as base 64 instead of image url in drag n drop option?
http://jsfiddle.net/durga598/w8kkc/414/
function handleDrop(e) {
// this / e.target is current target element.
e.preventDefault();
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
var img = document.querySelector('#images img.img_dragging');
var setImageWidth = 100,
setImageHeight = 100;
var imgObj = new Image();
imgObj.crossOrigin = 'Anonymous';
imgObj.onload = function(oImg) {
var tempCanvas = document.createElement('CANVAS');
var tempCtx = tempCanvas.getContext('2d');
var height = tempCanvas.height = this.naturalHeight;
var width = tempCanvas.width = this.naturalWidth;
tempCtx.drawImage(this, 0, 0);
var dataURL = tempCanvas.toDataURL();
fabric.Image.fromURL(dataURL, function(img) {
img.set({
width: width,
height: height,
scaleX: setImageWidth / width,
scaleY: setImageHeight / height,
left: e.layerX,
top: e.layerY,
})
canvas.add(img);
})
}
imgObj.src = img.src;
return false;
}
You need to create an image object and convert that to base64 data using toDataURL of canvas element. Then use fabric.Image.fromURL to add that image data to fabric canvas. Here is updated fiddle.

KineticJS: no method '_addId' in anonymous function

So, trying to work through the KineticJS.Image tutorial, but I run into an issue.
This works:
$(document).ready( function() {
var icon = new Image();
icon.onload = function() {
var stage = new Kinetic.Stage({
container: 'canvas',
width: 730,
height: 700,
});
var layer = new Kinetic.Layer();
var im = new Kinetic.Image({
x: -14,
y: -13,
image: icon,
width: 30,
height: 30
});
layer.add(im);
stage.add(layer);
};
icon.src = '#{asset_path "icons.png"}';
});
this, which very nearly the tutorial code, does not:
$(document).ready( function() {
var stage = new Kinetic.Stage({
container: 'targetCanvas',
width: 730,
height: 700,
});
var layer = new Kinetic.Layer();
var icon = new Image();
icon.onload = function() {
var im = new Kinetic.Image({
image: icon,
width: 30,
height: 30,
});
layer.add(im);
stage.add(layer);
};
icon.src = '#{asset_path "designer_icons.png"}';
});
It throws:
Uncaught TypeError: Object #<Object> has no method '_addId' kinetic.js:28
Kinetic.Container.add
Kinetic.Stage.add
icon.onload
I could have something Seriously Messed up in my environment, since this is in a serious hack job of a project (Rails w/Backbone,Require,Bootstrap and Kinetic), and I really don't know javascript or various libraries, so I'm fumbling around in the dark.
Any ideas what's causing this and how to fix it?
It seems stage is not initialized as a Kinetic.Node properly. Could you make it sure this exists?
<div id="targetCanvas"></div>
and also, please make it sure you are using version 4.3.1?
I don't see 4.3.1 has that line.
If the above does not help, please post your example, so that I can take a look at it.

Can I make a bookmarklet put some text into the clipboard?

Say I wanted to have bit of text (actually 4 different addresses) that I'd like to be able to easily (and frequently) paste. Is there a way I can make a bookmarklet that will put those addresses into the clipboard?
I'd like to be able to click the appropriate one, then right click + Paste.
Yes it's possible, have a look at zeroclipboard (note: requires flash). Also see this previous question.
Try building a Firefox extension instead of a bookmarklet. Mozilla XUL (extension language) lets you do copy-paste. Another option is a Java Applet.
http://brooknovak.wordpress.com/2009/07/28/accessing-the-system-clipboard-with-javascript/
Method with no third-party libraries
While zeroclipboard could potentially work, this method will allow you to visually select an element and automatically copy the inner text to your clipboard without having to download any third-party libraries. It is based on this function by Arne Hartherz and modified to work both in HTTPS and HTTP contexts.
Readable version:
var overlay = document.createElement('div');
Object.assign(overlay.style, {
position: 'fixed',
top: 0,
left: 0,
width: '100vw',
height: '100vh',
zIndex: 99999999,
background: 'transparent',
cursor: 'crosshair'
});
document.body.append(overlay);
function copyToClipboard(textToCopy) {
// navigator clipboard api needs a secure context (https)
if (navigator.clipboard && window.isSecureContext) {
// navigator clipboard api method'
return navigator.clipboard.writeText(textToCopy);
} else {
// text area method
let textArea = document.createElement("textarea");
textArea.value = textToCopy;
// make the textarea out of viewport
textArea.style.position = "fixed";
textArea.style.left = "-999999px";
textArea.style.top = "-999999px";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
return new Promise((res, rej) => {
// here the magic happens
document.execCommand('copy') ? res() : rej();
textArea.remove();
});
}
};
function getElement(event) {
overlay.style.pointerEvents = 'none';
var element = document.elementFromPoint(event.clientX, event.clientY);
overlay.style.pointerEvents = 'auto';
return element;
}
document.addEventListener('mousemove', function(event) {
var element = getElement(event);
if (!element) return;
var position = element.getBoundingClientRect();
Object.assign(overlay.style, {
background: 'rgba(0, 128, 255, 0.25)',
outline: '1px solid rgba(0, 128, 255, 0.5)',
top: '' + position.top + 'px',
left: '' + position.left + 'px',
width: '' + position.width + 'px',
height: '' + position.height + 'px'
});
});
overlay.addEventListener('click', function(event) {
var element = getElement(event);
var text = element.textContent || element.value;
text = text.replace(/\n[ \n]+\n/g, "\n").replace(/\n\n+/g, "\n\n").replace(/^\n+|\n+$/g, '');
if (!text.match("\n")) text = text.replace(/^ +| +$/, '')
copyToClipboard(text);
document.body.removeChild(overlay);
});
Minified version for use in bookmarklet:
javascript:void function(){function a(a){if(navigator.clipboard&&window.isSecureContext)return navigator.clipboard.writeText(a);else{let b=document.createElement("textarea");return b.value=a,b.style.position="fixed",b.style.left="-999999px",b.style.top="-999999px",document.body.appendChild(b),b.focus(),b.select(),new Promise((a,c)=>{document.execCommand("copy")?a():c(),b.remove()})}}function b(a){c.style.pointerEvents="none";var b=document.elementFromPoint(a.clientX,a.clientY);return c.style.pointerEvents="auto",b}var c=document.createElement("div");Object.assign(c.style,{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:99999999,background:"transparent",cursor:"crosshair"}),document.body.append(c);document.addEventListener("mousemove",function(a){var d=b(a);if(d){var e=d.getBoundingClientRect();Object.assign(c.style,{background:"rgba(0, 128, 255, 0.25)",outline:"1px solid rgba(0, 128, 255, 0.5)",top:""+e.top+"px",left:""+e.left+"px",width:""+e.width+"px",height:""+e.height+"px"})}}),c.addEventListener("click",function(d){var e=b(d),f=e.textContent||e.value;f=f.replace(/\n[ \n]+\n/g,"\n").replace(/\n\n+/g,"\n\n").replace(/^\n+|\n+$/g,""),f.match("\n")||(f=f.replace(/^ +| +$/,"")),a(f),document.body.removeChild(c)})}();

Resources