How to set time scale zoom in ChartJS?
I have following example data for a line chart:
[
{
x: 'Mon Sep 29 2018 14:26:53 GMT+0100',
y: 100
},
{
x: 'Mon Oct 15 2018 10:40:31 GMT+0100',
y: 400
}
]
My goal is to set a certain time frame as default and change it's range and zoom dynamically. If there is no data to show, it's fine.
I'm using the chartjs-plugin-zoom which allows me to pan freely on the x axis which is very good. Unfotunately the zoom is set on user events via this plugin.
Basically I want to have buttons to switch between time scalings and then pan on the x axis.
My question is, do I need to set the "limits" in ChartJS itself and let the plugin only pan? If yes, how to do this "freely" not considering the data (ChartJS tries to fit all data in the view, correct me if I'm wrong)
I tried the zoom options on the plugin, but they do not seem to affect anything:
zoom: {
enabled: true,
drag: false,
mode: '',
rangeMin: {
x: moment().format(),
y: null
},
rangeMax: {
x: moment().add(7, 'day').format(),
y: null
}
}
Thank you!
See also questions close to this topic
-
Why is my JavaScript object property inaccessible, when it IS, in fact, defined?
Here is the object. It is a second-level object in the data tree:
user: { userId: 3, username: 'aragorn', },
My React component is destructuring its parent object and making it available to the entire component. When I render the full user object using this code:
<p className="small"> {`Submitted by ${JSON.stringify(user)}`} </p>
I get a complete stringified object with all of user's properties:
When I try to access only the 'username' property from the 'user' object:
<p className="small"> {`Submitted by ${JSON.stringify(user.username)}`} </p>
I get this error:
Have you ever faced this weird issue before?
For further study, here is the full data object. This is coming from a mock data object being exported from a neighboring file in the same app. No network requests to a backend or anything, so there shouldn't be any async stuff going on here (I may be wrong):
{ title: "The Hefalump's Tale", page: '32', line: '1', author: 'Joni E. Driskill', genre: 'Sci-fi', type: 'Motivational', content: 'The grass is greener on the other side, unless, in actuality and reality, it is not. I guess in that case, you can just give up on anything nice in life.', claps: 23, id: 4, user: { userId: 3, username: 'aragorn', }, comments: [ { commentId: 0, quoteId: 0, content: 'Comment content', userId: 'userId', claps: 2, date: 2, }, { commentId: 1, quoteId: 1, content: 'Comment content', userId: 'userId', claps: 4, date: 1, }, { commentId: 2, quoteId: 2, content: 'Comment content', userId: 'userId', claps: 12, date: 0, }, ],
},
And HERE is my React component, called 'Meta,' bringing in the 'quote' object as a prop. The primary line in question is toward the bottom, but feel free to look at my props destructuring, too, if you like:
import React from 'react'; import Clap from '../mechanics/Clap'; import Report from '../mechanics/Report'; const Meta = ({ quote: { content, title, author, page, line, genre, type, claps, id, user, }, }) => ( <div className="discussion-meta mb2"> <h1>“{content}”</h1> <hr /> <div className="columns is-spaced-around pb3 text-align-left"> <div className="column"> <h3>{title}</h3> <p> <small>by {author}</small> </p> {page ? <p> <small>page {page}{line ? `, line ${line}` : ''}</small> </p> : null } </div> <div className="column text-align-right"> <p> <span className="tag-purple small">{genre}</span> </p> <p> <span className="tag-green small">{type}</span> </p> </div> </div> <div className="columns"> <div className="column"> <p className="small"> {`Submitted by ${JSON.stringify(user.username)}`} </p> </div> </div> <div className="columns"> <div className="column"> <Clap claps={claps} /> </div> <div className="column"> <Report id={id} /> </div> </div> </div> ); export default Meta;
I've recreated in CodeSandbox, and it works! WTF! https://codesandbox.io/s/4q9nlywl1x
-
Mongoose Save Nested Array of Objects - Node.js
I've created my model and can save an array of objects by manually listing them out, however this won't work in production because my array will not always be the same size.
Below is an example of my code. The issue I'm having when saving an array of objects under the stackRank field.
If anyone has any suggestions that would be great and a life saver!
Mongoose Model
const MySchema = mongoose.Schema({ userId: {type: mongoose.Schema.Types.ObjectId, ref: 'User', require: true}, startDate: {type: Date, require: true}, endDate: {type: Date, require: false}, length: {type: Number, require: true}, inProgress: {type: Boolean, require: true, default: true}, stackRank:[{ appUsers: {type: mongoose.Schema.Types.ObjectId, ref: 'Users', require: true} }] });
Saving Code in Express
const mySchema = new MySchema({ userId: req.body.userId, startDate: today, length: req.body.startLength, stackRank: [ //TODO this is the part I need to change {appUsers: Array[0]}, {appUsers: Array[1]}, {appUsers: Array[2]} ] }); instantComp.save() .then((result) => { console.log('result from save', result) }) .catch(err => console.log('error promise all', err))
Desired Functionality
Instead of saving each value of the array individually for the field appUsers nested in stackRank, I want to be able to save the entire array at once because it will not always have a length of three. It will almost always vary in length so while the code I've written works for an array of this size, it won't actually function properly for me.
-
Android WebView: how to scroll to an <a name=here> position
I'm loading a self-created HTML page into a
WebView
in an Android app.The HTML page contains a tag like
<a name="here"></a>
somewhere in the middle.After loading that page, I'd like to be able to programmatically scroll to that position, as if I had clicked on a
<a href="#here">here</a>
link.I tried with
loadURL
and withloadDataWithBaseURL
, with every possible parameter combinations that I could think of, without success.Note 1: I want to be able to scroll to that position after the page has been already displayed.
Note 2: I cannot use
scrollTo(x,y)
because I don't know the y position of that<a name="here">
anchor within the page. If I could figure out the y position in the page of that<a name>
tag, that would also solve the problem, but I don't know how to find that y value either.(P.S. I'm loading the self-created HTML page by calling
loadDataWithBaseURL(null, _html, null, null, null);
where _html is the string with my HTML page) -
Title in top column charts
I have a problem with using headings on the top of the columns using the bar chart. In some moments shows the title, and other moment does not show ...
Here my Print!
chart = new Highcharts.Chart({ "chart": { "renderTo": "container_adwords_cpa_alpes_666-664-4444", "type": "column", "animation": false }, "title": { "text": "Alpes.One - CPA (Formul\u00e1rio | Chatbot | Whatsapp)" }, "colors": ["#1d6c3f", "#003f23", "#68a9dc", "#007b5a", "#e4452b", "#ba0d00", "#004b76", "#b6740c", "#1b964e", "#f79969", "#fdc076", "#24a1ae", "#e46a2b", "#ff7754", "#83ccb0", "#6ecbd6", "#ec9631", "#65c07f", "#147bb6", "#005a64"], "series": [{ "name": "2018", "data": [575, 360.818182, 194.285714, 410.1, 212, 161.92, 344.846154, 203.639, 824.268, 130.406333, 323.399231, 657.198889] }, { "name": "2019", "data": [1236.88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }], "xAxis": { "categories": ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"], "labels": { "style": { "fontSize": "15px" } } }, "yAxis": { "min": 0, "title": { "text": "Quantidade" } }, "legend": { "align": "center", "verticalAlign": "bottom" }, "tooltip": { "formatter": function() { return '' + this.x + ': R$ ' + this.y.toFixed(2).replace('.', ',').replace(/(\d)(?=(\d{3})+\,)/g, "$1."); } }, "plotOptions": { "column": { "dataLabels": { "enabled": true, "crop": true, "overflow": "none", "style": { "fontSize": "14px" }, "formatter": function() { return 'R$ ' + this.y.toFixed(2).replace('.', ',').replace(/(\d)(?=(\d{3})+\,)/g, "$1."); } } } } });
-
Format & localize date labels in charts_flutter time series chart
I have following time series in charts_flutter:
charts.Series<DatumPoint, DateTime>( id: 'Series', colorFn: (_, __) => charts.MaterialPalette.red.shadeDefault, domainFn: (DatumPoint point, _) => point.date, measureFn: (DatumPoint point, _) => point.value, data: p, )
and this is how my
TimeSeriesChart
has been created:@override Widget build(BuildContext context) { return charts.TimeSeriesChart( widget.seriesList, animate: widget.animate, selectionModels: [ charts.SelectionModelConfig( type: charts.SelectionModelType.info, changedListener: _onSelectionChanged, ) ], domainAxis: charts.EndPointsTimeAxisSpec(), behaviors: [ charts.LinePointHighlighter( showHorizontalFollowLine: charts.LinePointHighlighterFollowLineType.none, showVerticalFollowLine: charts.LinePointHighlighterFollowLineType.nearest, dashPattern: [1, 1]), charts.SelectNearest( eventTrigger: charts.SelectionTrigger.tapAndDrag, ), ], ); } }
I would like to format start & end ticker on domain Axis using localize
DateTime
format e.g.DateFormat.yMMMd(Localizations.localeOf(context).languageCode).format(date)
How can I achieve this?
-
Horizontal Stacked Bar Chart Values Not Aligning Properly
I am brand new to Python and am in a class for this language. I have searched for the last week for a solution to this but have not been successful.
I have a horizontally stacked bar chart that I cannot get the labels to properly place themselves.
import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np plt.rcParams['figure.figsize'] = 25,12 fig = plt.figure() ax = plt.subplot() respond = [2, 19, 46, 46, 55, 61, 78, 121, 150, 158, 169] no_response = [0, 3, 51, 70, 32, 19, 61, 81, 109, 105, 132] y = np.arange(len(respond)) plt.barh(y, respond, color='teal') plt.barh(y, no_response, color='brown', left=respond) y_labels = ['label_1', 'Label_2', 'Label_3', 'Label_4', 'Label_5', 'Label_6', 'Label_7', 'Label_8', 'Label_9', 'Label_10', 'Label_11'] plt.yticks(y, y_labels) plt.title('MASS Responses by Group') plt.xlabel('Responses') plt.ylabel('GD Group') responding = mpatches.Patch(color='teal', label='Responded') not_responding = mpatches.Patch(color='brown', label='No Response') plt.legend(handles=[responding, not_responding], loc='lower right') rects = ax.patches # For each bar: Place a label for rect in rects: # Get X and Y placement of label from rect. x_value = rect.get_width() y_value = rect.get_y() + rect.get_height()/2.5 # Number of points between bar and label. Change to your liking. space = 25 # Vertical alignment for positive values ha = 'center' # If value of bar is negative: Place label left of bar if x_value < 0: # Invert space to place label to the left space *= -1 # Horizontally align label at right ha = 'center' # Use X value as label and format number with one decimal place label = "{:.0f}".format(x_value) # Create annotation ax.annotate( label, # Use `label` as label (x_value, y_value), # Place label at end of the bar xytext=(space, 0), # Horizontally shift label by `space` textcoords="offset points", # Interpret `xytext` as offset in points va='baseline', # Vertically center label ha='center', # Horizontally align label differently for positive and negative values. color='white', # Font color of the label fontweight='bold') # Bolded #fig.savefig('test.png', bbox_inches='tight', pad_inches=2) plt.show()
You can see when the chart is run that the values are aligning in reference to the X axis value. I need them to align to their respective rectangle bar.
-
Some bars of the bar graph are disappearing from Chart.js
I am trying to make a chart using Chart.js, I am making a bar chart, and simply by adding some data, some of these bars disappear. I realized that this SOMETIMES happens when I put equal values in the date fields. Can someone help me? Please?
var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["Janeiro", "Fevereiro", "Março", "Abril"], datasets: [ { label: "Indicados", yAxisID: 'yAxis1', backgroundColor: "#56D9FE", data: [5,3,3,4] }, { label: "Instalados", yAxisID: 'yAxis1', backgroundColor: "#5FE3A1", data: [3,4,6,4] }, { label: "Vendas", yAxisID: 'yAxis2', backgroundColor: "#A3A0FB", data: [50, 45, 80, 60] }, { label: "Bônus", yAxisID: 'yAxis2', backgroundColor: "#FEC163", data: [30, 10, 25, 35], } ] }, options: { responsive: true, //responsividade maintainAspectRatio: true, lineWidth: 0.1, aspectRatio: 3, //tamanho legend: { display: true, position: 'bottom' // Posição das legendas }, scales: { yAxes: [ { id: 'yAxis1', position: 'left' }, { id: 'yAxis2', position: 'right' } ] } } });
-
Multiple pie charts with chartjs
Trying to show two pie charts in the same page but it doesn't work. This is the code:
<html> <head> </head> <body> <canvas id="tests-summary" height="50px"></canvas> <canvas id="exceptions-summary" height="50px"></canvas> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script> <script> // Tests pie chart var testSummaryData = { datasets: [{ data: [ 55, 114, 152 ], backgroundColor: [ "#82bc41", "#bbbbbb", "#c8102e" ], label: 'My dataset' // for legend }], labels: [ "Passed", "Skipped", "Failed" ] }; var testSummaryOptions = { events: false, animation: { duration: 500, easing: "easeOutQuart", onComplete: function () { var ctx = this.chart.ctx; ctx.font = "bold 16px Arial"; ctx.textAlign = 'center'; ctx.textBaseline = 'bottom'; this.data.datasets.forEach(function (dataset) { for (var i = 0; i < dataset.data.length; i++) { var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model, total = dataset._meta[Object.keys(dataset._meta)[0]].total, mid_radius = model.innerRadius + (model.outerRadius - model.innerRadius)/2, start_angle = model.startAngle, end_angle = model.endAngle, mid_angle = start_angle + (end_angle - start_angle)/2; var x = mid_radius * Math.cos(mid_angle); var y = mid_radius * Math.sin(mid_angle); ctx.fillStyle = '#fff'; if (i == 1){ // Darker text color for lighter background ctx.fillStyle = '#444'; } var percent = String(Math.round(dataset.data[i]/total*100)) + "%"; //Don't Display If Legend is hide or value is 0 if(dataset.data[i] != 0 && dataset._meta[0].data[i].hidden != true) { ctx.fillText(dataset.data[i], model.x + x, model.y + y); // Display percent in another line, line break doesn't work for fillText ctx.fillText(percent, model.x + x, model.y + y + 15); } } }); } } }; var testSummaryCanvas = $("#tests-summary"); var testSummaryPieChart = new Chart(testSummaryCanvas, { type: 'pie', data: testSummaryData, options: testSummaryOptions }); var exceptionsSummaryData = { datasets: [{ data: [ 55, 114 ], backgroundColor: [ "#82bc41", "#bbbbbb" ], label: 'My dataset' // for legend }], labels: [ "Passed", "Skipped" ] }; var exceptionsSummaryOptions = { events: false, animation: { duration: 500, easing: "easeOutQuart", onComplete: function () { var ctx = this.chart.ctx; ctx.font = "bold 16px Arial"; ctx.textAlign = 'center'; ctx.textBaseline = 'bottom'; this.data.datasets.forEach(function (dataset) { for (var i = 0; i < dataset.data.length; i++) { var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model, total = dataset._meta[Object.keys(dataset._meta)[0]].total, mid_radius = model.innerRadius + (model.outerRadius - model.innerRadius)/2, start_angle = model.startAngle, end_angle = model.endAngle, mid_angle = start_angle + (end_angle - start_angle)/2; var x = mid_radius * Math.cos(mid_angle); var y = mid_radius * Math.sin(mid_angle); ctx.fillStyle = '#fff'; if (i == 1){ // Darker text color for lighter background ctx.fillStyle = '#444'; } var percent = String(Math.round(dataset.data[i]/total*100)) + "%"; //Don't Display If Legend is hide or value is 0 if(dataset.data[i] != 0 && dataset._meta[0].data[i].hidden != true) { ctx.fillText(dataset.data[i], model.x + x, model.y + y); // Display percent in another line, line break doesn't work for fillText ctx.fillText(percent, model.x + x, model.y + y + 15); } } }); } } }; var exceptionsCanvas = $("#exceptions-summary"); var exceptionsPieChart = new Chart(exceptionsCanvas, { type: 'pie', data: exceptionsSummaryData, options: exceptionsSummaryOptions }); </script> </body> </html>
-
dynamically fill a json variable
This is going to be a bit complicated, i hope i can explain it well. I am trying to dynamically fill my chartjs with data from a database. The data is Volume specific (Letter and usage in percent).
Due to the flexibility of the database structure, i decided to put all volume informations in one single cell, which divides each volume with a whitespace and the letter and percentage with a comma. Which looks like this:
Note: The last volume has no letter because it is "system reserved"
Now i need to put this data dynamically inside a json variable so i can push it to my chart. At the moment it looks like this:
var jsonData = { "L": [{"y": 100}, {"y": 50}, {"y": 40}], "C": [{"y": 61}, {"y": 39}, {"y": 59}], "": [{"y": 33}, {"y": 97}, {"y": 67}] }
But those values and volume letters are hardcoded. So i need to split up my php string, which includes the volumes, and somehow pass it for every entry to the json variable. For now i got this to split up the string:
function splitStringByWhitespace($value) { $value = preg_split('/\s+/', $value); return $value; } foreach ($resultPerformanceInfo as $row) { $diskUsages = $row['diskUsage']; $diskUsagesSplitted = splitStringByWhitespace($diskUsages); for ($i = 0; $i < sizeof($diskUsagesSplitted); $i++) { $explode2 = explode(",", $diskUsagesSplitted[$i]); $json2[] = $explode2; } }
if i make
echo json_encode($json2)
it prints:[["L","100"],["C","61"],["","33"],["L","50"],["C","39"],["","97"],["L","40"],["C","59"],["","67"]]
which is a start i guess. Now i need to select each letter once, and every value which belongs to the correspondending letter.Here i an illustration of what i mean:
Note:(I already managed to implement a dropdown which gets all volume letters so i can switch the chart between the diffrent volumes. So there is no help needed for this.) For those who wonder, this is what it looks like at the moment:
Also i should mention, that the json variable needs to be dynamically extendable because it is possible that there are more than 3 volumes per cell. I know it may be a bit much to ask but i struggle since 3 days and i can't manage to do it. Could someone show me how to do such thing?
-
Zoom in and out, but keep svg centered
I have a world map in svg format, and am using a viewbox to focus on Africa. I have two buttons for zooming in and zooming out:
<rect class="button" x="75" y="170" onclick="zoom(0.8)" style="width:25px; height:20px; fill:khaki"/> <rect class="button" x="100" y="170" onclick="zoom(1.25)" style="width:25px; height:20px; fill:khaki"/>
In an external .js file, I have code that pans and zooms, which I found in Peter Collingridge's online tutorial:
var transformMatrix = [1, 0, 0, 1, 0, 0]; var svg = document.getElementById('map-svg'); var viewbox = svg.getAttributeNS(null, "viewBox").split(" "); var centerX = parseFloat(viewbox[2]) / 2; var centerY = parseFloat(viewbox[3]) / 2; var matrixGroup = svg.getElementById("matrix-group"); function pan(dx, dy) { transformMatrix[4] += dx; transformMatrix[5] += dy; var newMatrix = "matrix(" + transformMatrix.join(' ') + ")"; matrixGroup.setAttributeNS(null, "transform", newMatrix); } function zoom(scale) { for (var i = 0; i < transformMatrix.length; i++) { transformMatrix[i] *= scale; } transformMatrix[4] += (1 - scale) * centerX; transformMatrix[5] += (1 - scale) * centerY; var newMatrix = "matrix(" + transformMatrix.join(' ') + ")"; matrixGroup.setAttributeNS(null, "transform", newMatrix); }
Everything works just as I want it to, except for one thing. When I zoom in, Africa "jumps" to the right, and when I zoom out, it "jumps" to the left. How can I zoom in and out, with Africa staying in the center of the viewbox?
-
What api is responsible for setting custom page zoom levels in firefox?
I am trying to create a firefox browser extension for setting custom zoom values. Please, what is the api for setting custom page zooms values for firefox?
-
How to zoom, in MGL mapView, so that the view encompasses one "object" on the map
I have an MGLPolyline on a mapbox map and want to make is so when the user taps on the line it centers around the line and zooms in as much as possible so that the full line is on display. Currently, I make the centering work well but the zoom works randomly:
I just set it to max zoom, However, this is of course not what I want.
Bellow is where I want to add the zoom amount:
func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) { print("Tapped") mapView.setCenter(CLLocationCoordinate2D(latitude: annotation.coordinate.latitude, longitude: annotation.coordinate.longitude), zoomLevel: mapView.zoomLevel, animated: true) mapView.deselectAnnotation(annotation, animated: false) }
-
Android: How to determine size of an ImageView on the screen in inches
Here's some background information. I'm making an Android app that requires an ImageView to be shown on the screen in the same physical size (xInches by yInches) regardless of the device that the image is being shown on. The problem I'm having is that the size of the ImageView, by default, changes size depending on the current screen resolution and the screen size.
What I need is a function that:
- Has inputs of the ImageView I need to resize, the x (in inches) of the preferred size, and the y (in inches) of the preferred size
- Computes the pixel dimensions of something x by y inches (the magic I need to figure out how to implement)
- Returns the calculated x and y dimensions in dpi/px or something that I can easily apply to the ImageView
I'm kind of new to developing for Android, so I'm not 100% familiar with the different coordinate systems, such as px vs dpi, but all I'm looking for is a way to correspond these coordinate systems with physical coordinates.
By the way, I'm only using inches because I live in the U.S. However, what I mean to say is any unit that measures in physical space rather than screen space.
Thanks for your help!
-
clip-path dynamic transformations to fill container
I'm working on a react component I would like to be able to pass any image along with its dimensions, a clip-path calculated from an x, y width, and height for a rectangular region. This part I have working well. Then I would like to scale this clipped region back to fill a div, at the moment I have this div just the original image dimensions to keep it simple. I have the scaling part calculating properly but cannot work out the math to translate the scaled clip-path region. Here is my component (in Typescript):
interface RootProps { links: Link[]; } interface RootState { } class Root extends React.Component<RootProps, RootState> { constructor(props) { super(props); this.state = { } } pp = (x: number, y: number): string => { return x + "% " + y + "%" } renderClippedImage = (name: string, x: number, y: number, width: number, height: number) => { let iWidth = 600; let iHeight = 360; let p1 = { x: (x / iWidth) * 100, y: (y / iHeight) * 100 } let p2 = { x: (x / iWidth) * 100, y: ((y + height) / iHeight) * 100 } let p3 = { x: ((x + width) / iWidth) * 100, y: ((y + height) / iHeight) * 100 } let p4 = { x: ((x + width) / iWidth) * 100, y: (y / iHeight) * 100 } let clipPathString = 'polygon(' + this.pp(p1.x, p1.y) + ', ' + this.pp(p2.x, p2.y) + ', ' + this.pp(p3.x, p3.y) + ', ' + this.pp(p4.x, p4.y) + ')'; let pX = (x) / iWidth; let pY = (y) / iHeight; let portionCoverageX = (width) / iWidth; let portionCoverageY = (height) / iHeight; let scaleX = 1; let scaleY = 1; if (portionCoverageX > 0) { scaleX = 1 / portionCoverageX; } if (portionCoverageY > 0) { scaleY = 1 / portionCoverageY; } let translateX = -(((pX * scaleX) / 2) * 100); //this doesn't work let translateY = 0; //similar issues getting this to work let pathClipping = { WebkitClipPath: clipPathString, clipPath: clipPathString, transform: 'translateX(' + translateX + '%) translateY(' + translateY + '%) scaleX(' + scaleX + ') scaleY(' + scaleY + ')' } console.log({ name: name, pX: pX, pY: pY, portionCoverageX: portionCoverageX, portionCoverageY: portionCoverageY, scaleX: scaleX, scaleY: scaleY, translateX: translateX, translateY: translateY }) return ( <div style={{ textAlign: 'center', width: '100%', backgroundColor: 'lightseagreen' }}> <b>{name}</b><br /> <div style={{ display: 'inline-block', width: 640, height: 360, backgroundColor: 'darkslateblue' }}> <img width="640" height="360" src="https://placekitten.com/640/360" style={pathClipping} /> </div> </div> ) } render() { return ( <div style={{textAlign: 'center'}}> <b>Original</b><br /> <img width="640" height="360" src="https://placekitten.com/640/360" /> <br /> {this.renderClippedImage("one", 80, 100, 200, 100)} <br /> {this.renderClippedImage("two", 50, 50, 150, 100)} <br /> {this.renderClippedImage("three", 300, 10, 300, 340)} </div> ) } } ReactDOM.render(<Root />, document.getElementById('mount-node'));
And here is a codepen, where you can see, my current math actually works for scenario 3, but it needs to work for 1, 2 and any other legitimate region combo as well.
https://codepen.io/anon/pen/xMWGRO
The specific line I think I am strugling with is this:
let translateX = (((pX * iWidth) / 2)); //this doesn't work for all examples
translateY is a similar issue, any help would be most appreciated.
-
Synchronize zooming between to bubble clouds
I have two D3 bubble clouds, under different divs, and I'd like to apply the same zoom factor to both as one zooms either graph. Cannot figure out how to get the zoomFactor, and eventually how to apply it to the other cloud.