Fabric.js - problem with drawing multiple images zindex - html

I'm using this script:
var canvas = new fabric.Canvas('game_canvas', { selection: false });
fabric.Image.fromURL('images/bg.jpg', function(img) {
img.set('left', 1024/2).set('top', 600/2).set('zindex', 0);
canvas.add(img);
});
fabric.Image.fromURL('images/panel-2-bg-l-r.png', function(img) {
img.set('left', 262/2).set('top', (390/2)+110).set('zindex', 1);
canvas.add(img);
});
fabric.Image.fromURL('images/player-board.png', function(img) {
img.set('left', 254/2).set('top', (122/2)).set('zindex', 2);
canvas.add(img);
});
fabric.Image.fromURL('images/player-board-top-red.png', function(img) {
img.set('left', 203/2).set('top', (109/2)).set('zindex', 3);
canvas.add(img).bringToFront(img);
});
3rd image draw is working properly and showing one on top of the other. But if I add 4th one it's hiding behind 3rd. If I specify zindex of the image it's still under 3rd only.
What is wrong with this? Am I doing something wrong here? Please help.
Thanks
Peter

There are couple of issues here.
1) You can't change zindex of images by setting their zindex property. Fabric images simply don't have such property and changing it doesn't change z index of images on canvas. This makes all those .set('zindex', 0), .set('zindex', 1), etc. pretty much a no-op.
2) bringToFront works as expected here, bringing last image all the way to the top of the drawing stack. But the problem is that "images/player-board-top-red.png" image which you're loading last is not guaranteed to be the last one added. Those 4 requests are asynchronous; they are coming in any order, and so callbacks are executed in any order as well. In my test, for example, the last image comes second, callback executes, image is brought to the front, but is then "overwritten" by following 2 callbacks.
How to make last image render on top? Well, we can simply check that all images are loaded before attempting to bring last one to the top:
var img4;
// ...
function checkAllLoaded() {
if (canvas.getObjects().length === 4) {
canvas.bringToFront(img4);
}
}
// ...
fabric.Image.fromURL('images/1.png', function(img) {
img.set('left', 0).set('top', 0);
canvas.add(img);
checkAllLoaded(img);
});
// load other images, making sure to include `checkAllLoaded` in callback
fabric.Image.fromURL('images/4.png', function(img) {
img4 = img.set('left', 0).set('top', 0);
canvas.add(img);
checkAllLoaded(img);
});
By the way, don't forget that you can pass an object to set method like so:
img.set({ left: ..., top: ... });
And since set is chainable and returns reference to an instance, you can even pass it to add like so:
canvas.add(img.set({ left: ..., top: ... }));
Hope this helps.

You can use canvas.insertAt(object,index); instead of canvas.add(object) to set object's zIndex as per your choice.
Also you can get any object by using:
canvas_object = canvas.item(index);
If you want to bring that object in front, use:
canvas_object.bringForward()
//or
canvas_object.bringToFront()

Related

html2canvas on esri Map - layers moves

I am trying to create a function in the Angular system which will produce an image of the map using html2canvas
The following is the current function:
window.emapComponent.service.getMap('mapApi').then((map) => {
html2canvas(document.getElementById("mapApi"), { useCORS: true }).then(function (canvas) {
canvas.screenshotDataURI = canvas.toDataURL("image/jpg", 0.5);
canvas.toBlob(function (blob) {
saveAs(blob, oRequest.fileName)
});
});
})
What happens is that in the system itself, as soon as I drag the map with the mouse, the photo comes out weird (file attached)-
I noticed in the elements of html that although I see the objects of the layers adjusted to the map, in practice the div itself is dragged from place to place and this is what I get in the picture
I would be happy to help with this

Custom Loading Cursor

I want to know if there is a way to change the "progress" cursor's loading animation. Like changing the cursor like in this CSS-Trick post.
Two ways to achieve what you want.
The CSS way
If you want to completely customize the cursor, you can use cursor which accept images (in your case, a .gif !)
._show-loader:hover {
cursor: url('http://i117.photobucket.com/albums/o72/redfenderstrat/Debian_Rotate.gif');
}
I like this approach since I prefer keeping JS out of my pure design things as much as possible.
The jQuery way
If you need to add an animation after user's cursor (to make this more natural since people does not have the same cursor), this jQuery alternative will make the image stick to the cursor.
var $showLoader = $('._show-loader');
$showLoader.on('mousemove', function(e) {
var cursorPos = {
left: e.pageX + 20,
top: e.pageY + 20,
}
$("._cursor-onLoad").css({
left: cursorPos.left,
top: cursorPos.top
});
});
$showLoader.on('mouseenter', function() {
$('._cursor-onLoad').css({
display: 'block',
})
});
$showLoader.on('mouseleave', function() {
$('._cursor-onLoad').css({
display: 'none',
})
});
JSFiddle here
I doesn't really like this alternative since it does this 2002-sluggish effect.

jCanvas imageSmoothingEnabled not working

So I am trying to build a game with pixel art in html using jCanvas. However, when I try to disable imageSmoothing in order to leave the pixels sharp, nothing happens.
$(function() {
$('canvas').drawImage({
source: 'http://i.imgur.com/Y2o59.png',
x:400, y:250,
width: 160, height: 160,
imageSmoothingEnabled: false,
});
});
Edit: Added random piece of pixel art to make it easier to test.
Figured it out.
First of all, its imageSmoothing: false, not imageSmoothingEnabled: false.
Second, you still need to enable smoothing on the context, like this:
var ctxbgd = document.getElementById('background').getContext("2d");
ctxbgd.imageSmoothingEnabled = false;
ctxbgd.webkitImageSmoothingEnabled = false;
ctxbgd.mozImageSmoothingEnabled = false;
There, no smoothing.

dragging and dropping onto a jquery slider - posting position to server

I'm trying to implement dragging an item onto a jquery slider. For example, if the item is dropped onto 86% of the slider I would like to POST this position to the server so the item can be place 86% along the result set on the server.
How do you detect dropping onto a jQuery slider and the percentage POSTed to the server?
Since I'm not so good at explaining things, I made a jsFiddle for you. Although this might not be exactly what your looking for, it should be a good starting point!
Here's the code :
$(function () {
//the draggable object
$("#dragobject").draggable();
//Prepare the slider
var range = 100,
sliderDiv = $("#slider");
// Activate the UI slider
sliderDiv.slider({
min: 0,
max: range,
create : function(){
$(this).find(".ui-slider-handle").hide();
}
});
// Number of tick marks on slider
var position = sliderDiv.position(),
sliderWidth = sliderDiv.width(),
minX = position.left,
maxX = minX + sliderWidth,
tickSize = sliderWidth / range;
//Set slider as droppable
sliderDiv.droppable({
//on drop
drop: function (e, ui) {
var finalMidPosition = $(ui.draggable).position().left + Math.round($("#dragobject").width() / 2);
//If within the slider's width, follow it along
if (finalMidPosition >= minX && finalMidPosition <= maxX) {
var val = Math.round((finalMidPosition - minX) / tickSize);
sliderDiv.slider("value", val);
alert(val + "%");
//do ajax update here to set the position
/*$.ajax({
type: "POST",
url: url,
data: val,
success: function () {
//congrats
},
dataType: dataType
});*/
}
}
});
});
And here's the jsFiddle link : jsFiddle example
Hope it helps,
Marc.
SOURCES :
Jquery slider that slides while mouse move,
jQuery UI slider
Since you are using jQuery, lets assume you are using jQuery UI for your drag and drop. First read this: http://api.jqueryui.com/droppable/#event-drop
Then realize that you get the offset position of the dropped element relative to the droppable container as part of the event. This would be where you could compute that into percentage if you needed.
For example, dropped at position left -> 90px of a container that you know to be 100px wide means 90% is your magic number.
Or if you are using native drag and drop, check out this simple edit: http://jsbin.com/ezuke/3283/edit . If you pop a console log on the event in the drop event, you will see that it also exposes the offset of where you dropped it and you could again consume that in your calculation of %.

Keep a Google Maps v3 Map hidden, show when needed

Is there a way of preventing a Google Maps (JS, v3) map being displayed from the get-go? I'm doing some pre-processing and would like to show my 'Loading' spinner until everything is good to go (more eloquently put, hide the map -- e.g. the container div – until all pre-processing is complete – at which point, show the map).
Hooking up the map's idle event doesn't help that much, since the map is already displayed when this event hits.
I know that the container div gets inline-styled by GMaps after loading, my first idea was to clear out the style attribute (whilst listening to the idle event), but it would be interesting to see if there is a way of creating the map and not displaying it until all pre-processing is done.
Maybe by using an argument to the new google.maps.Map constructor, or a MapOption ?
Any thoughts on this?
Thank you in advance!
Also remember to call:
google.maps.event.trigger(map, 'resize');
if you have changed the size of the <div>. A display:none <div> has no size.
Or you could just hide it like with css visablility or css opacity.
$("#GoogleMap").css({ opacity: 0, zoom: 0 });
initialize();
google.maps.event.addListener(map,"idle", function(){
$('#Loader').hide();
$("#GoogleMap").css({ opacity: 1, zoom: 1 });
});
This works for me. I'm using the JQuery library.
$(document).ready(function(){
$('#Checkbox').click(function(){
$('#googleMapDiv').toggle();
initialize(); // initialize the map
});
});
another way to show the hidden map when map is first time rendering the <div> is to set style: visibility.
When firstly hidden, use visibility = hidden; to show use visibility = visible
the reason is: visibility:hidden means that the contents of the element will be invisible, but the element stays in its original position and size.
this works fine for me, I use jquery tabs
setTimeout(function() {
google.maps.event.trigger(map, "resize");
map.setCenter(new google.maps.LatLng(default_lat, default_lng));
map.setZoom(default_map_zoom);
}, 2000);
om this link https://code.google.com/p/gmaps-api-issues/issues/detail?id=1448
This will work
google.maps.event.addListener(map, "idle", function ()
{
google.maps.event.trigger(map, 'resize');
});
better way:
gmap.redraw = function() {
gmOnLoad = true;
if(gmOnLoad) {
google.maps.event.trigger(gmap, "resize");
gmap.setCenter(gmlatlng);
gmOnLoad = false;
}
}
and in show click event:
$("#goo").click(function() {
if ($("#map_canvas").css("display") == "none") {
$("#YMapsID").toggle();
$("#map_canvas").toggle();
if (gmap != undefined) {
gmap.redraw();
}
}
});
depending on what you are doing another posibility could be to have multiple bools you set to true when each process is done.
For example:
if you have a geocode service running which you want to wait for, you could have a var called
GeoState
and in the result part of the geocoder set GeoState to true,
then have a timed function check if all the services have returned true, when they have, make the map visible.