Angular - Can Leaflet measurement tool mute a layer's interactivity? - javascript

I'm using Leaflet.Measure for measuring areas and distances and I also have several layers on a map. When you click on a layer, the onclick function is being fired and a popup appears. When I start to measure a new area and click on a map layer, the popup appears again and I cannot measure area further. Is there any possibility to mute layer's interactivity, while I'm using measurement tool?
I tired to import my Angular service class into a measuring plugin to change layer's onclick behaviour, but it didn't work.
Here's a part of Leaflet.Measure plugin code, which I have modified:
import { MapService} from './app/services/map.service';
L.MeasureAction = L.Handler.extend({
_onMouseClick: function (event) {
MapService.enablePopupOpen = false; // if it's set to false, then popup won't open
//default plugin code
var latlng = event.latlng || this._map.mouseEventToLatLng(event);
if (this._lastPoint && latlng.equals(this._lastPoint)) {
return;
}
if (this._trail.points.length > 0) {
var points = this._trail.points;
points.push(latlng);
var length = points.length;
this._totalDistance += this._getDistance(points[length - 2], points[length - 1]);
this._addMeasurePoint(latlng);
//this._addMarker(latlng);
if (this.options.model !== "area") {
this._addLable(latlng, this._getDistanceString(this._totalDistance), "leaflet-measure-lable");
}
} else {
this._totalDistance = 0;
this._addMeasurePoint(latlng);
this._addMarker(latlng);
if (this.options.model !== "area") {
this._addLable(latlng, L.Measure.start, "leaflet-measure-lable");
}
this._trail.points.push(latlng);
}
this._lastPoint = latlng;
this._startMove = false;
},
...
})

Related

how to check if Marker is in the region displayed on the screen in react native maps

I have list of items displayed horizontally in FlatList at the bottom and all the markers in the map. Now user can zoom in/out map freely or click on any marker and the bottom FlatList is scrolling to item. User can also scroll FlatList and based on the index marker is selected. When the list is large and user has manually zoom in the map.
Now problem is user can zoom any where on map and when user swipes List below and changes the item index, I need to be able to check if that marker is on the screen or not and if not zoom to that marker.
so for I was able to zoom manually with region with below code.
const animateMapToRegion = (region = null, duration = 1000) => {
if (region) {
mapRef.current.animateToRegion(region, duration);
}
};
This animation only needs to be done if marker is not already on screen. I checked documentation and was not able to find any function to check whether marker is on the screen or not.
I want to animate only if marker is not visible on screen. Please assist.
I ended up by adding my own implementation for both iOS and Android.
Add below method in AIRGoogleMapManager.m
RCT_EXPORT_METHOD(isMarkerWithinScreen:(nonnull NSNumber *)reactTag
position:(CLLocationCoordinate2D)position
resolver: (RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
id view = viewRegistry[reactTag];
if (![view isKindOfClass:[AIRGoogleMap class]]) {
RCTLogError(#"Invalid view returned from registry, expecting AIRMap, got: %#", view);
} else {
AIRGoogleMap *mapView = (AIRGoogleMap *)view;
GMSVisibleRegion region = [mapView.projection visibleRegion];
GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] initWithRegion:region];
resolve(#{#"visible": #([bounds containsCoordinate:position])});
}
}];
}
Add below method in AirMapModule.java
#ReactMethod
public void isMarkerWithinScreen(final int tag, ReadableMap coordinate, final Promise promise) {
final ReactApplicationContext context = getReactApplicationContext();
final double lat = coordinate.getDouble("latitude");
final double lng = coordinate.getDouble("longitude");
final LatLng position = new LatLng(lat,lng);
UIManagerModule uiManager = context.getNativeModule(UIManagerModule.class);
uiManager.addUIBlock(new UIBlock()
{
#Override
public void execute(NativeViewHierarchyManager nvhm)
{
AirMapView view = (AirMapView) nvhm.resolveView(tag);
if (view == null)
{
promise.reject("AirMapView not found");
return;
}
if (view.map == null)
{
promise.reject("AirMapView.map is not valid");
return;
}
LatLngBounds currentScreen = view.map.getProjection().getVisibleRegion().latLngBounds;
boolean onScreen = currentScreen.contains(position);
WritableMap visibleJson = new WritableNativeMap();
visibleJson.putBoolean("visible", onScreen);
promise.resolve(visibleJson);
}
});
}
add finally add below in node_modules/react-native-maps/lib/components/MapView.js
isMarkerWithinScreen(marker) {
if (Platform.OS === 'android') {
return NativeModules.AirMapModule.isMarkerWithinScreen(
this._getHandle(),
marker.coordinate
);
} else if (Platform.OS === 'ios') {
return this._runCommand('isMarkerWithinScreen', [marker.coordinate]);
}
return Promise.reject('isMarkerWithinScreen not supported on this platform');
}
Now you can use this as,
const marker = //your marker;
const visibility = await mapRef.current.isMarkerWithinScreen(marker);
const {visible} = visibility;
console.log('visible-->', visible); //If visible is true marker is on screen otherwise its not.

Highcharts 6.0 Synchronization Bug

I'm trying to use Highcharts Synchronization for a slightly complex chart. I've gotten synchronization to work just fine on graphs with just 1 series for other plots.
You can check out the example here: http://jsfiddle.net/nhng5827/o9uh2jqy/42/
I've dumbed down my complex chart to just a few points, and usually the chart has 6 lines as opposed to 4. As you can see, the tooltip only appears on the right side of the graph, and everything is delayed. I also do not want the callout box to have any numbers read out if the tooltip is not hovered the specific lines.
I've done a fair bit of research and have implemented some code I've seen that allows for charts with 2 series to be synchronized (http://jsfiddle.net/mjsdnngq/72/), however I think the biggest difference in mine is that the series only go to about half of the actual chart.
$('#container').bind('mousemove touchmove touchstart', function (e) {
var chart,
points,
i,
secSeriesIndex = 1;
for (i = 0; i < Highcharts.charts.length; i++) {
chart = Highcharts.charts[i];
e = chart.pointer.normalize(e); // Find coordinates within the chart
points = [chart.series[0].searchPoint(e, true), chart.series[1].searchPoint(e, true),chart.series[2].searchPoint(e, true),chart.series[3].searchPoint(e, true)]; // Get the hovered point
if (points[0] && points[1]&& points[2]&& points[3]) {
// if (!points[0].series.visible) {
// points.shift();
// secSeriesIndex = 0;
// }
// if (!points[secSeriesIndex].series.visible) {
// points.splice(secSeriesIndex,1);
// }
if (points.length) {
chart.tooltip.refresh(points); // Show the tooltip
chart.xAxis[0].drawCrosshair(e, points[0]); // Show the crosshair
chart.xAxis[0].drawCrosshair(e, points[3]); // Show the crosshair
}
}
}
});
/**
* Override the reset function, we don't need to hide the tooltips and crosshairs.
*/
Highcharts.Pointer.prototype.reset = function () {
return undefined;
};
Highcharts.Point.prototype.highlight = function (event) {
this.onMouseOver(); // Show the hover marker
this.series.chart.tooltip.refresh([points[0],points[1],points[2],points[3]]); // Show the tooltip
this.series.chart.xAxis[0].drawCrosshair(event, this); // Show the crosshair
};
/**
* Synchronize zooming through the setExtremes event handler.
*/
function syncExtremes(e) {
var thisChart = this.chart;
if (e.trigger !== 'syncExtremes') { // Prevent feedback loop
Highcharts.each(Highcharts.charts, function (chart) {
if (chart !== thisChart) {
if (chart.xAxis[0].setExtremes) { // It is null while updating
chart.xAxis[0].setExtremes(e.min, e.max, undefined, false, { trigger: 'syncExtremes' });
}
}
});
}
}
Any help would be immensely appreciated.
To correctly synchronize charts, you have to clear points state on every mousemove event:
Highcharts.each(chart.series, function(s) {
Highcharts.each(s.points, function(p) {
p.setState('');
});
});
Live demo: http://jsfiddle.net/BlackLabel/cvb6pwsu/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Point#setState
Also, please take a look at this example: http://jsfiddle.net/BlackLabel/6f37b42q/, it can be useful for you.

How to navigate tooltips popup by clicking custom buttons outside Chart.js v2 canvas?

Discussion on mobile usability under Chart.js v2 library,
Can we simulate click event on those "score points" in the RadarChart?
I'm asking this because,
Desktop view and tablet view looks quite okay for "score points" navigation by clicking on those points within Chart to trigger external interactivity by returned index.
an popular example can be find is
$('#ChartV2').click(function(e) {
var activePoints = myRadarChart.getElementsAtEvent(e);
var firstPoint = activePoints[0];
console.log(firstPoint);
if (firstPoint !== undefined){
alert(firstPoint._index);
//so then we can use
// index to hide show results in the html elements out of canvas , etc
}
});
But if you look into mobile view,
under responsive:true, the chart will be much smaller by auto resizing,
thus the points inside radarchart can be very small for mobile click,
same with labels, everything will be smaller and harder to click on.
Could it be customizable to let user navigate those "score points"
(initially triggered by click on canvas manually )
can it be indirectly trigger by
external "prev", "next" navigation buttons
on left and right side of the Radarchart
such as those slider / carousel navigation buttons?
You can do this by utilizing the chart instance methods
Script
var myRadarChart = new Chart(ctx, {
...
(function (chart) {
var helpers = Chart.helpers;
var currentDatasetIndex;
var currentPointIndex;
$('#ChartV2').click(function (e) {
// try getting an element close to the click
var activePoints = chart.getElementAtEvent(e);
var firstPoint = activePoints[0];
if (firstPoint === undefined) {
// otherwise pick the first visible element
helpers.each(chart.data.datasets, function (dataset, datasetIndex) {
if (firstPoint === undefined && this.isDatasetVisible(datasetIndex)) {
var meta = this.getDatasetMeta(datasetIndex);
firstPoint = meta.data[0];
}
}, chart);
}
// need this check as we may have 0 visible elements
if (firstPoint !== undefined) {
currentDatasetIndex = firstPoint._datasetIndex;
currentPointIndex = firstPoint._index;
$('#prev, #next').removeAttr('disabled');
updateView();
}
});
$('#prev').click(function () {
// we add (n - 1) and do a modulo n to move one step back in an n element array.
if (currentPointIndex === 0)
currentDatasetIndex = (currentDatasetIndex + chart.data.datasets.length - 1) % chart.data.datasets.length;
currentPointIndex = (currentPointIndex + chart.data.labels.length - 1) % chart.data.labels.length;
updateView();
});
$('#next').click(function () {
currentPointIndex = (currentPointIndex + 1) % chart.data.labels.length;
if (currentPointIndex === 0)
currentDatasetIndex = (currentDatasetIndex + 1) % chart.data.datasets.length;
updateView();
});
// this (hoisted) function will update the text and show the tooltip
function updateView() {
$('#value').text(
chart.data.datasets[currentDatasetIndex].label + ' : ' +
chart.data.labels[currentPointIndex] + ' : ' +
chart.data.datasets[currentDatasetIndex].data[currentPointIndex]);
// we mess around with an internal variable here - this may not work with a new version
chart.tooltip._active = [ chart.getDatasetMeta(currentDatasetIndex).data[currentPointIndex] ];
chart.tooltip.update();
chart.render();
}
}(myRadarChart));
If you want this functionality only for small screens, just add a screen size check to the above chart click handler and hide the buttons and label using media queries.
Fiddle - http://jsfiddle.net/uxqL6rwf/

Paper.js Background Rasterization Glitches

We are building an image editor of sorts using Paper.js. We have a queue on the side of the Paper.js canvas that allows switching between images. Each time we switch between images, we want to flatten all the annotations (rasterize) onto the image just being edited.
Each time we switch images, this method is called, which rasterizes the current image and annotations to a data URL. (If we revisit this image, a raster from this data URL will be displayed.)
var flattenToDataUrl = function() {
layerAsRaster = paper.project.layers[0].rasterize(); // Layer to Paper.js Raster object
layerAsRaster.visible = false; // Attempt to set not visible
var dataString = layerAsRaster.toDataURL();
return dataString;
};
Then we end up calling this method, which changes out the image we're editing:
var setCanvasImage = function(imageObject) {
if(imageObject != null)
{
imageHeight = imageObject.height;
var imageWidth = imageObject.width;
// Set up HTMLImage
var imageElement = new Image(imageObject.width, imageObject.height);
if(_.has(imageObject, 'imageData')) { // Came as 64 bit data
imageElement.src = 'data:image/png;base64,' + imageObject.imageData;
} else if(_.has(imageObject, 'imageUrl')) { // Came as URL
imageElement.src = imageObject.imageUrl;
}
// Add image to Paper.js canvas
imageElement.onload = function(event) {
// Initialize Paper.js on the canvas
paper.setup(canvas);
raster = new paper.Raster(imageElement, new paper.Point(canvas.width / 2, canvas.height / 2));
setUpNotes();
selectedItems = new paper.Group(); // Since Paper.js has been setup we can now initialize this Group
registerCanvasEvents(); // Panning, zooming, moving selected items, deselecting all selected items
fitToPage();
};
}
};
So, this changes out the image, but when I move my mouse into the canvas after selecting a different image in the queue, it glitches to the image we were just on (with its annotations) until I do something like pan, zoom, etc. Then I see the image I selected and am truly working with.
Removing the flattenToDataUrl() functionality makes the queue work seamlessly. So it seems to me something is fishy there. We are generating a Paper.js Raster object in that method. Rasters seem to automatically add themselves. I attempt to curb this with a call to
layerAsRaster.visible = false;
but to no avail.
What is causing this glitchy behavior and how do I prevent it?
Update
For clarity (hopefully) and completeness, I've decided to post the whole PaperFunctions class we use in conjunction with React, which hosts our <canvas> element. There's a lot of code, and a lot of cleanup to do, especially in registerCanvasEvents(). Bear with this learning beginner. Also it's several hundred lines, so it may be helpful to paste it into your favorite editor. Entry points include setCanvas which is called in componentDidMount of the React class with the <canvas> element, and canvasSetImage which is called from the queue. I agree from bmacnaughton's answer that it's weird to call paper.setup(canvas) every time we load a new image. I'm currently investigating the right solution to this, the right place to put it. setCanvas seems logical but when I drag the image to move it in that setup, it leaves a trail of images in its wake. Anyway, here's PaperFunctions.js:
var JQueryMousewheel = require('jquery-mousewheel')($);
var SimplePanAndZoom = require('./SimplePanAndZoom.js');
var panAndZoom = new SimplePanAndZoom();
var selectedItems;
// We use selection here in two distinct ways.
// An item may be Paper.js selected but not in the selection group.
// This is because we want to show it is selectable.
// A blue bounding box indicates it is selectable.
// A green bounding box indicates it has actually been selected and added to selectedItems.
// Only things in selectedItems are actually operated on.
// So the event handlers in this method basically set up whether or not the item is in selectedItems (and therefore will be operated on for moving, resizing, deleting, etc.).
// That is, the event handlers here are concerned with displaying to the user the status of selection for the item - whether or not it will be operated on when events actually happen on the selectedItems Group.
var registerItemEvents = function(item) {
// Boolean flag for mouseup to know if was drag or click
var dragged;
// For tracking if dragging or clicking is happening
item.on('mousedown', function(e) {
dragged = false;
});
// On click toggle selection
item.on('mouseup', function(event) {
event.stopPropagation(); // Only for item applied to
event.preventDefault();
if(!dragged) {
var justAdded = addIfNotInSelectedItems(item);
if(!justAdded) { // Item was in selection group, remove it
item.remove();
paper.project.activeLayer.addChild(item);
this.selectedColor = paper.project.activeLayer.selectedColor;
//item.selected = false;
}
}
});
// Show as selectable even after has been deselected
item.on('mousemove', function(event) {
this.selected = true;
})
// If not selected, on mouse enter show that it is selectable
item.on('mouseenter', function(event) {
if(!this.selected) {
this.selected = true;
}
});
// If not selected, on mouse leave remove indicator that is selectable
item.on('mouseleave', function(event) {
var isInSelectedItems = selectedItems.getItem(item);
if(this.selected && isInSelectedItems == null) {
this.selected = false;
}
});
// On drag, move item
item.on('mousedrag', function(event) {
dragged = true;
// If user starts dragging automatically select the item
addIfNotInSelectedItems(item);
});
}
var addIfNotInSelectedItems = function(item) {
var isInSelectedItems = selectedItems.getItem(item);
if(isInSelectedItems == null) { // Item not currently in selection group, add it
selectedItems.addChild(item);
item.selectedColor = 'green';
item.selected = true;
return true; // Was added, return true
} else {
return false; // Already in, return false
}
}
var registerCanvasEvents = function() {
if(paper.view != null && canvas != null) {
// Zoom on mousewheel
$(canvas).mousewheel(function(event) {
event.preventDefault();
var mousePosition = new paper.Point(event.offsetX, event.offsetY);
var viewPosition = paper.view.viewToProject(mousePosition);
var returnedValues = panAndZoom.changeZoom(paper.view.zoom, (event.deltaY * -1), paper.view.center, viewPosition, 1.1);
var newZoom = returnedValues[0];
var offset = returnedValues[1];
paper.view.zoom = newZoom;
paper.view.center = paper.view.center.add(offset);
});
// For tracking if dragging or clicking is happening
var dragged;
paper.project.layers[0].on('mousedown', function(e) { // TODO should be layer 0 in long run?
dragged = false;
});
// Pan on mouse drag
/*paper.project.layers[0].on('mousedrag', function(event) { // TODO should be layer 0 in long run?
if(!event.event.ctrlKey && !event.event.altKey && !event.event.shiftKey) { // No keys (that we use) can be pushed
dragged = true; // We're panning, we don't wish to deselect all items as we would do with a click
paper.view.center = panAndZoom.changeCenter(paper.view.center, event.delta.x, event.delta.y, 0.7);
//event.preventDefault();
}
});*/
// Move selected items on mouse drag
selectedItems.on('mousedrag', function(event) {
event.stopPropagation(); // Don't propogate up or it will register as a pan event
event.preventDefault();
dragged = true; // We're panning, we don't wish to deselect all items as we would do with a click
this.translate(new paper.Point(event.delta.x, event.delta.y));
});
// If was a click and not a drag, deselect selected items
paper.project.layers[0].on('mouseup', function(event) {
if(!dragged) {
var removedItems = selectedItems.removeChildren(); // Remove from selection group, which also removes from display
paper.project.activeLayer.addChildren(removedItems); // Return to display
// Reset selection colors for showing selectable
for(var i =0; i < removedItems.length; i++) {
removedItems[i].selectedColor = paper.project.activeLayer.selectedColor;
removedItems[i].selected = false;
}
}
});
// Initial path object, will be reset for new paths after Alt is released
var path = newPath();
var paths = [];
paths.push(path);
// On mousedown add point to start from
paper.project.layers[0].on('mousedown', function(event) {
if(event.event.altKey && !event.event.ctrlKey) { // Alt key to add a path, but disallow attempting to add text at the same time
if(paths[paths.length-1].lastSegment == null) {
//path.add(event.point, event.point);
paths[paths.length-1].add(event.point, event.point);
} else {
//path.add(path.lastSegment.point, path.lastSegment.point);
paths[paths.length-1].add(paths[paths.length-1].lastSegment.point, paths[paths.length-1].lastSegment.point);
}
}
});
// On mousedrag add points to path
paper.project.layers[0].on('mousedrag', function(event) {
if(event.event.altKey && !event.event.ctrlKey) { // Alt key to add a path, but disallow attempting to add text at the same time
if(event.event.shiftKey) { // Use shift key for freeform
//path.add(event.point);
paths[paths.length-1].add(event.point);
} else { // Default of straight line added to path
//path.lastSegment.point = event.point;
paths[paths.length-1].lastSegment.point = event.point;
}
}
}.bind(this));
var tool = new paper.Tool();
var startDragPoint;
// Capture start of drag selection
paper.tool.onMouseDown = function(event) {
if((event.event.ctrlKey && event.event.shiftKey) || (event.event.ctrlKey && event.event.altKey)) {
startDragPoint = new paper.Point(event.point);
}
};
paper.tool.onMouseDrag = function(event) {
// Panning
if(!event.event.ctrlKey && !event.event.altKey && !event.event.shiftKey) { // No keys (that we use) can be pushed
dragged = true; // We're panning, we don't wish to deselect all items as we would do with a click
paper.view.center = panAndZoom.changeCenter(paper.view.center, event.delta.x, event.delta.y, 0.7);
//event.preventDefault();
}
// Show box indicating the area that has been selected
// For moving area and whiting out area
if((event.event.ctrlKey && event.event.shiftKey) || (event.event.ctrlKey && event.event.altKey)) {
dragged = true;
var showSelection = new paper.Path.Rectangle({
from: startDragPoint,
to: event.point,
strokeColor: 'red',
strokeWidth: 1
});
// Stop showing the selected area on drag (new one is created) and up because we're done
showSelection.removeOn({
drag: true,
up: true
});
}
};
// Capture start of drag selection
paper.tool.onMouseUp = function(event) {
if((event.event.ctrlKey && event.event.shiftKey) || (event.event.ctrlKey && event.event.altKey)) {
var endDragPoint = new paper.Point(event.point);
if(event.event.ctrlKey && event.event.shiftKey) { // Whiteout area
whiteoutArea(startDragPoint, endDragPoint);
} else if(event.event.ctrlKey && event.event.altKey) { // Move selected area
selectArea(startDragPoint, endDragPoint);
}
}
};
// Key events
paper.tool.onKeyUp = function(event) {
// Delete selected items on delete key
if(event.key == 'delete') {
selectedItems.removeChildren();
} else if (event.key == 'option') {
registerItemEvents(paths[paths.length-1]);
// Start a new path
paths.push(newPath());
}
}
}
}
// These variables are scoped so that all methods in PaperFunctions can access them
var canvas; // Set by setCanvas
var imageHeight; // Set by setCanvasImage
var raster;
var toolsSetup = false;
var setCanvas = function(canvasElement) {
canvas = canvasElement;
paper.setup(canvas);
};
var setCanvasImage = function(imageObject) {
if(imageObject != null)
{
imageHeight = imageObject.height;
var imageWidth = imageObject.width;
// Set up HTMLImage
var imageElement = new Image(imageObject.width, imageObject.height);
if(_.has(imageObject, 'imageData')) { // Came as 64 bit data
imageElement.src = 'data:image/png;base64,' + imageObject.imageData;
} else if(_.has(imageObject, 'imageUrl')) { // Came as URL
imageElement.src = imageObject.imageUrl;
}
// Add image to Paper.js canvas
imageElement.onload = function(event) {
//canvas.height = $(document).height()-3; // Set canvas height. Why do this here and not in the React component? Because we set the width here too, so we're keeping those together. Perhaps in the future this will be changed when we are responsive to window resizing.
//scalingFactor = canvas.height / imageObject.height; // Determine the ratio
//canvas.width = imageElement.width * scalingFactor; // Scale width based on height; canvas height has been set to the height of the document
// Initialize Paper.js on the canvas
paper.setup(canvas);
raster = new paper.Raster(imageElement, new paper.Point(canvas.width / 2, canvas.height / 2));
//setUpLineAndFreeFormDrawing(); // TODO once we cycle through images will we need to reset this for each new image or can we do this just once?
setUpNotes(); // TODO once we cycle through images will we need to reset this for each new image or can we do this just once?
selectedItems = new paper.Group(); // Since Paper.js has been setup we can now initialize this Group
registerCanvasEvents(); // Panning, zooming, moving selected items, deselecting all selected items
fitToPage();
};
}
};
var fitToPage = function() {
if(paper.view != null && canvas != null) {
// Fit image to page so whole thing is displayed
var scalingFactor = canvas.height / imageHeight; // Constant representation of the ratio of the canvas size to the image size
var zoomFactor = scalingFactor / paper.view.zoom; // Dynamic representation of the zoom needed to return to viewing the whole image in the canvas
// Reset the center point to the center of the canvas
var canvasCenter = new paper.Point(canvas.width/2, canvas.height/2);
paper.view.center = canvasCenter;
// Zoom to fit the whole image in the canvas
var returnedValues = panAndZoom.changeZoom(paper.view.zoom, -1, canvasCenter, canvasCenter, zoomFactor); // Always pass -1 as the delta, not entirely sure why
var newZoom = returnedValues[0];
var offset = returnedValues[1];
paper.view.zoom = newZoom;
paper.view.center = paper.view.center.add(offset);
}
};
var addImage = function(imageDataUrl) {
if(paper.view != null) {
var img = document.createElement("img");
img.src = imageDataUrl;
var presentMomentForId = new Date().getTime() + "-image"; // For purposes of having unique IDs
img.id = presentMomentForId;
img.hidden = true;
document.body.appendChild(img);
var raster = new paper.Raster(presentMomentForId);
registerItemEvents(raster);
}
};
var setUpLineAndFreeFormDrawing = function() {
if(paper.project != null) {
// Initial path object, will be reset for new paths after Alt is released
var path = newPath();
var paths = [];
paths.push(path);
// On mousedown add point to start from
paper.project.layers[0].on('mousedown', function(event) {
if(event.event.altKey && !event.event.ctrlKey) { // Alt key to add a path, but disallow attempting to add text at the same time
if(paths[paths.length-1].lastSegment == null) {
//path.add(event.point, event.point);
paths[paths.length-1].add(event.point, event.point);
} else {
//path.add(path.lastSegment.point, path.lastSegment.point);
paths[paths.length-1].add(paths[paths.length-1].lastSegment.point, paths[paths.length-1].lastSegment.point);
}
}
});
// On mousedrag add points to path
paper.project.layers[0].on('mousedrag', function(event) {
if(event.event.altKey && !event.event.ctrlKey) { // Alt key to add a path, but disallow attempting to add text at the same time
if(event.event.shiftKey) { // Use shift key for freeform
//path.add(event.point);
paths[paths.length-1].add(event.point);
} else { // Default of straight line added to path
//path.lastSegment.point = event.point;
paths[paths.length-1].lastSegment.point = event.point;
}
}
}.bind(this));
// Each time Alt comes up, start a new path
paper.tool.onKeyUp = function(event) {
if(event.key == "option") {
registerItemEvents(paths[paths.length-1]);
// Start a new path
paths.push(newPath());
}
};
}
};
// Establishes default line style
var newPath = function() {
var path = new paper.Path();
path.strokeColor = 'black';
path.strokeWidth = 10;
return path;
};
var note = "";
var setNote = function(newNote) {
note = newNote;
};
var setUpNotes = function() {
if(paper.project != null) {
paper.project.layers[0].on('mousedown', function(event) { // TODO should be layer 0 in long run?
if(event.event.ctrlKey && !event.event.altKey && !event.event.shiftKey) { // Only Ctrl key to add text
// Add text box
var textBox = new paper.PointText(event.point);
textBox.justification = 'left';
textBox.fillColor = 'black';
textBox.fontSize = 60;
textBox.content = note;
registerItemEvents(textBox);
}
});
}
};
var selectArea = function(startDragPoint, endDragPoint) {
var rasterTopLeftCorner = new paper.Point(raster.bounds.topLeft);
var adjustedStartDragPoint = new paper.Point(startDragPoint.x - rasterTopLeftCorner.x, startDragPoint.y - rasterTopLeftCorner.y);
var adjustedEndDragPoint = new paper.Point(endDragPoint.x - rasterTopLeftCorner.x, endDragPoint.y - rasterTopLeftCorner.y);
var boundingRectangleRasterCoordinates = new paper.Rectangle(adjustedStartDragPoint, adjustedEndDragPoint);
var boundingRectangleCanvasCoordinates = new paper.Rectangle(startDragPoint, endDragPoint);
var selectedArea = raster.getSubRaster(boundingRectangleRasterCoordinates);
var whitedOutSelection = new paper.Shape.Rectangle(boundingRectangleCanvasCoordinates);
whitedOutSelection.fillColor = 'white';
whitedOutSelection.insertAbove(raster); // Whiteout just above the image we're working with
registerItemEvents(selectedArea);
}
var whiteoutArea = function(startDragPoint, endDragPoint) {
var whitedOutSelection = new paper.Shape.Rectangle(startDragPoint, endDragPoint);
whitedOutSelection.fillColor = 'white';
whitedOutSelection.insertAbove(raster); // Whiteout just above the image we're working with
}
var flattenToDataUrl = function() {
layerAsRaster = paper.project.layers[0].rasterize(); // TODO should be layer 0 in long run? // Layer to Paper.js Raster object
layerAsRaster.visible = false;
var dataString = layerAsRaster.toDataURL();
return dataString;
};
module.exports = {
setCanvas: setCanvas,
setCanvasImage: setCanvasImage,
fitToPage: fitToPage,
addImage: addImage,
setNote: setNote,
flattenToDataUrl: flattenToDataUrl
};
Additionally, here's the SimplePanAndZoom.js file for clarity. It uses minimal Paper functions, it mainly just does calculations:
// Based on http://matthiasberth.com/articles/stable-zoom-and-pan-in-paperjs/
var SimplePanAndZoom = (function() {
function SimplePanAndZoom() { }
SimplePanAndZoom.prototype.changeZoom = function(oldZoom, delta, centerPoint, offsetPoint, zoomFactor) {
var newZoom = oldZoom;
if (delta < 0) {
newZoom = oldZoom * zoomFactor;
}
if (delta > 0) {
newZoom = oldZoom / zoomFactor;
}
// Zoom towards offsetPoint, not centerPoint (unless they're the same)
var a = null;
if(!centerPoint.equals(offsetPoint)) {
var scalingFactor = oldZoom / newZoom;
var difference = offsetPoint.subtract(centerPoint);
a = offsetPoint.subtract(difference.multiply(scalingFactor)).subtract(centerPoint);
}
return [newZoom, a];
};
SimplePanAndZoom.prototype.changeCenter = function(oldCenter, deltaX, deltaY, factor) {
var offset;
offset = new paper.Point(-deltaX, -deltaY);
offset = offset.multiply(factor);
return oldCenter.add(offset);
};
return SimplePanAndZoom;
})();
module.exports = SimplePanAndZoom;
Thanks.
I'm taking some guesses here but I'll address some problems in the code that will hopefully address the behavior you're seeing.
First, I presume paper.project.layers[0] is paper.project.activeLayer. Once that has been rasterized 1) the raster is added to the layer and setting visible = false does cause it to disappear when an update is done.
Second, when you invoke paper.setup(canvas) in imageElement.onload you create a new paper project. This project starts out as the active project and makes the previous project "disappear". So when you create a raster with raster = new paper.Raster(...) it goes into the new project, not the old project.
So now there is a hidden (.visible = false) raster in the old project (let's call it project1) and a new version of it in project2.
I'm not sure if this is the intended behavior or not, but when you invoke paper.setup(canvas) for what seems to be the second time then paper seems to notice that they both refer to the same canvas and keeps project1 and project2 in sync. So creating the second project clears the first project's children array. And adding new paper.Raster(...) ends up adding the raster to project1 and project2.
Now I can't tell what the next piece of the puzzle is. You'd need to add some information like 1) where the mouse event handlers are setup and what they are attached to, 2) what setUpNotes() does, 3) what registerCanvasEvents() does, and 4) what fitToPage does.
There are a few globals created, imageHeight and raster that probably aren't intentional. And it's not clear why you need to use new Image() at all - paper.Raster() accepts URLs, including data URLs.
I was surprised paper cleared the first project. It's curious.
Version 2:
Let me take a stab at structuring this using layers. I'd suggest you get rid of multiple projects because having mouse event handlers attached to multiple projects that share the same canvas adds too much complexity.
So, in your code initialization: paper.setup(canvas). Do this once and only once.
Setup the initial image in the single layer initially created by paper.
// this will be inserted into the current layer, project.activeLayer
var raster = new paper.Raster(imageURL, paper.view.bounds.center);
When the image in your queue changes do something like:
// make the existing image/layer invisible
paper.project.activeLayer.visible = false;
// add a new layer which is inserted in the project and activated
var layer = new paper.Layer();
// the new layer is activated, create a raster for the image
var raster = new paper.Raster(imageURL, paper.view.bounds.center);
// now do your normal logic for editing, zooming, etc.
It's really a bit more complicated than that because you have a queue of images and you only want to create a layer the first time you visit an image. You could initialize all the rasters at the outset, something like:
var imageURLs = ["url to image1", "url to image2", "etc"];
imageURLs.forEach(function(url) {
new paper.Layer();
paper.project.activeLayer.visible = false;
new paper.Raster(url, paper.view.bounds.center);
});
// make the first layer visible and activate it
paper.project.layers[0].visible = true;
paper.project.layers[0].activate();
The preceeding code gives you a parallel array to the images in your queue so switching images is straightforward - there is no checking to see if that image has been created or not:
function setImage(index) {
paper.project.activeLayer.visible = false;
paper.project.layers[index].activate();
paper.project.layers[index].visible = true;
}
Finally, I would make sure my mouse handling wasn't causing me problems. From the new code you posted it looks like each project had a global tool that handled 'mousedown', 'mousedrag', and 'mouseup' events, another set of handlers for activeLayer for 'mousedown', 'mousedrag', and 'mouseup' events, and also selectedItems has a handler for 'mousedrag'. I can't keep track of what all the different handlers are supposed to do across projects. I'm guessing that these are the root issue with the flickering you saw.
I would likely just use paper.view.on for 'mousedown', 'mousedrag', and 'mouseup' events. When I get an event I would check to see if anything on the layer was hit by using the following:
paper.project.activeLayer.hitTest(event.point);
Being able to set events on the view is new for paper but very useful. There may be a few other tweaks necessary to handle highlighting unselected items. A relatively straightforward way to handle that is to have a group of selected items and a group of unselected items:
unSelectedGroup.on('mouseenter', function() {
unSelectedGroup.selected = true;
});
unSelectedGroup.on('mouseleave', function() {
unSelectedGroup.selected = false;
});
These should be safe across layers when only one layer is visible at a time. I would set up these group handlers when setting up the images, whether all up front or on an as-needed basis. Alternatively, you could also add paper.view.on('mousemove', ...) and handle the 'mouseenter' and 'mouseleave' events yourself using hitTest as shown above, but either approach should work.
I think using a layer-based approach to your images will keep things in sync. There are enough problems with the project-based approach and many different mouse event handlers that you'll be on more stable ground regardless.

Change position of tooltip in Google Chart

I have a google chart that I'm using where I have set the type of tooltip to be html in my options, like this:
tooltip: { isHtml: true }
Customizing the tooltip to look how I want has been the easy part, but getting the tooltip in the right position has surprisingly difficult. After a lot of searching, I found this answer on tooltip positioning, but cannot seem to get it working.
My javascript (aside from options) for creating the chart and dealing with tooltip positioning is as follows:
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
var container = document.querySelector('#chart_div > div:last-child');
function setPosition () {
var tooltip = container.querySelector('div.google-visualization-tooltip');
tooltip.style.top = 0;
tooltip.style.left = '-47px';
}
if (typeof MutationObserver === 'function') {
var observer = new MutationObserver(function (m) {
for (var i = 0; i < m.length; i++) {
console.log("mutation: " + m[i].type);
if (m[i].addedNodes.length) {
setPosition();
break; // once we find the added node, we shouldn't need to look any further
}
}
});
observer.observe(container, {
childList: true
});
} else if (document.addEventListener) {
container.addEventListener('DOMNodeInserted', setPosition);
} else {
container.attachEvent('onDOMNodeInserted', setPosition);
}
});
chart.draw(dataTable, options);
I'm using Google Chrome for testing right now, and if I put a debugger in the typeof MutationObserver snippet, I am getting in there and setting the observer, but it seems as though it never gets observed, as I am not even getting the console messages.
Any help would be very appreciated. My html element with the ID chart_div exists (and the chart is rendered there), so I am not sure what I am missing.

Categories

Resources