Filling D3.js Pie Graph with SQL Query - php

I am currently using D3.js to make a pie graph. The data is stored in a MSSQL database, which is then converted to JSON using PHP. Here is my code that does that
<?php
// Server Name
$myServer = "SRVR";
// Database
$myDB = "TestDB";
// If using Windows Authentication, get rid of, "'UID'=>$myUser, 'PWD'=>$myPass, "
// Notice that the latest driver uses sqlsrv rather than mssql
$conn = sqlsrv_connect('Database'=>$myDB));
// Change TestDB.vwTestData to YOURDB.dbo.YOURTABLENAME
$sql = "SELECT col, SUM(num) AS 'value'
FROM db
GROUP BY col";
$result = array();
do {
while ($row = sqlsrv_fetch_array($data, SQLSRV_FETCH_ASSOC)){
$result[] = $row;
}
} while ( sqlsrv_next_result($data) );
// This will output in JSON format if you try to hit the page in a browser
echo json_encode($result);
sqlsrv_free_stmt($data);
sqlsrv_close($conn);
?>
This works fine. I've tested it, and it outputs JSON in something like this:
[{"col":null,"value":247.9042254},{"col":"value1","value":16.8151576061},{"col":"value2","value":235.4833175609},{"col":"value3","value":2316.072432028},{"col":"value4","value":8904.4001532729}]
How can I put this in the graph? Here is my .js code
(function() {
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b"]);
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return // Something goes here I assume });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
d3.json("scripts/graphs/script.php", function(error, data) {
data.forEach(function(d) {
// Something needs to go here?
});
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.age); });
g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.age; });
});
})();
If someone could help me out, that would be great. Thanks!

I figured it out. I used this code and customized it for JSON
https://gist.github.com/enjalot/1203641
Here is what I got
(function() {
var w = 670, //width
h = 326, //height
r = 150, //radius
color = d3.scale.category20c(); //builtin range of colors
d3.json("script.php", function (data) {
var vis = d3.select("body")
.append("svg:svg") //create the SVG element inside the <body>
.data([data]) //associate our data with the document
.attr("width", w) //set the width and height of our visualization (these will be attributes of the <svg> tag
.attr("height", h)
.append("svg:g") //make a group to hold our pie chart
.attr("transform", "translate(" + r + "," + r + ")") //move the center of the pie chart from 0, 0 to radius, radius
var arc = d3.svg.arc() //this will create <path> elements for us using arc data
.outerRadius(r);
var pie = d3.layout.pie() //this will create arc data for us given a list of values
.value(function(d) { return d.value; }); //we must tell it out to access the value of each element in our data array
var arcs = vis.selectAll("g.slice") //this selects all <g> elements with class slice (there aren't any yet)
.data(pie) //associate the generated pie data (an array of arcs, each having startAngle, endAngle and value properties)
.enter() //this will create <g> elements for every "extra" data element that should be associated with a selection. The result is creating a <g> for every object in the data array
.append("svg:g") //create a group to hold each slice (we will have a <path> and a <text> element associated with each slice)
.attr("class", "slice"); //allow us to style things in the slices (like text)
arcs.append("svg:path")
.attr("fill", function(d, i) { return color(i); } ) //set the color for each slice to be chosen from the color function defined above
.attr("d", arc); //this creates the actual SVG path using the associated data (pie) with the arc drawing function
arcs.append("svg:text") //add a label to each slice
.attr("transform", function(d) { //set the label's origin to the center of the arc
//we have to make sure to set these before calling arc.centroid
d.innerRadius = 0;
d.outerRadius = r;
return "translate(" + arc.centroid(d) + ")"; //this gives us a pair of coordinates like [50, 50]
})
.attr("text-anchor", "middle") //center the text on it's origin
.text(function(d, i) { return data[i].col; }); //get the label from our original data array
})
})();
So what was wrong was that I wasn't connecting the key values from the JSON, to the variables in the JS. Here are the lines to change:
var vis = d3.select("<PUT DIV ID HERE>")
.value(function(d) { return d.<PUT NUMBER VALUE KEY NAME HERE>; });
.text(function(d, i) { return data[i].<PUT SLICE CATEGORY HERE>; });

I am not entirely certain what is not working about your code, but you could try something simple like:
d3.json("scripts/graphs/script.php", function(error, data) {
data.forEach(function(d) {
d.value = +d.value
});
var g...
Alternately, could you just call the php script and store the returned json object in a variable, then pass that variable to d3.json?

Related

PHP: d3.js script does not display anything

Problem: I've got the following code, that runs fine as a standalone .html file. Now, I wish to display this within a .php file. Inside the .php file, I've copy-pasted the same code.
There are some header/footer and other html in the main page where this .php file is to be displayed. However, when I run it But other than the line, "Testing", the chart does not display.
What additional changes should be done ?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<div>
<h4>Testing</h4>
</div>
<!-- <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?2.4.5"></script> -->
<script src="d3.v3.js"></script>
<!-- Source for example located at: http://bl.ocks.org/1203641 -->
<style type="text/css">
.slice text {
font-size: 16pt;
font-family: Arial;
}
</style>
<script>
var canvasWidth = 500, //width
canvasHeight = 700, //height
outerRadius = 200, //radius
color = d3.scale.category20(); //builtin range of colors
var dataSet = [
{"legendLabel":"Your child's Percentile", "magnitude":90},
{"legendLabel":"Ahead of your child", "magnitude":10},
// {"legendLabel":"Three", "magnitude":50},
// {"legendLabel":"Four", "magnitude":16},
// {"legendLabel":"Five", "magnitude":50},
// {"legendLabel":"Six", "magnitude":8},
// {"legendLabel":"Seven", "magnitude":30}
];
var vis = d3.select("body")
.append("svg:svg") //create the SVG element inside the <body>
.data([dataSet]) //associate our data with the document
.attr("width", canvasWidth) //set the width of the canvas
.attr("height", canvasHeight) //set the height of the canvas
.append("svg:g") //make a group to hold our pie chart
.attr("transform", "translate(" + 1.5*outerRadius + "," + 1.5*outerRadius + ")") // relocate center of pie to 'outerRadius,outerRadius'
// This will create <path> elements for us using arc data...
var arc = d3.svg.arc()
.outerRadius(outerRadius);
var pie = d3.layout.pie() //this will create arc data for us given a list of values
.value(function(d) { return d.magnitude; }) // Binding each value to the pie
.sort( function(d) { return null; } );
// Select all <g> elements with class slice (there aren't any yet)
var arcs = vis.selectAll("g.slice")
// Associate the generated pie data (an array of arcs, each having startAngle,
// endAngle and value properties)
.data(pie)
// This will create <g> elements for every "extra" data element that should be associated
// with a selection. The result is creating a <g> for every object in the data array
.enter()
// Create a group to hold each slice (we will have a <path> and a <text>
// element associated with each slice)
.append("svg:g")
.attr("class", "slice"); //allow us to style things in the slices (like text)
arcs.append("svg:path")
//set the color for each slice to be chosen from the color function defined above
.attr("fill", function(d, i) { return color(i); } )
//this creates the actual SVG path using the associated data (pie) with the arc drawing function
.attr("d", arc);
// Add a legendLabel to each arc slice...
arcs.append("svg:text")
.attr("transform", function(d) { //set the label's origin to the center of the arc
//we have to make sure to set these before calling arc.centroid
d.outerRadius = outerRadius + 50; // Set Outer Coordinate
d.innerRadius = outerRadius + 45; // Set Inner Coordinate
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle") //center the text on it's origin
.style("fill", "Purple")
.style("font", "bold 12px Arial")
.text(function(d, i) { return dataSet[i].legendLabel; }); //get the label from our original data array
// Add a magnitude value to the larger arcs, translated to the arc centroid and rotated.
arcs.filter(function(d) { return d.endAngle - d.startAngle > .2; }).append("svg:text")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
//.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")rotate(" + angle(d) + ")"; })
.attr("transform", function(d) { //set the label's origin to the center of the arc
//we have to make sure to set these before calling arc.centroid
d.outerRadius = outerRadius; // Set Outer Coordinate
d.innerRadius = outerRadius/2; // Set Inner Coordinate
return "translate(" + arc.centroid(d) + ")rotate(" + angle(d) + ")";
})
.style("fill", "White")
.style("font", "bold 12px Arial")
.text(function(d) { return d.data.magnitude; });
// Computes the angle of an arc, converting from radians to degrees.
function angle(d) {
var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
return a > 90 ? a - 180 : a;
}
</script>
</meta>
</head>
</html>
Works fine for me. The only difference is that I replaced your script tags with remote ones
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://dimplejs.org/dist/dimple.v2.1.0.min.js"></script>
If you are including this file from another PHP file, delete doctype, html, body and head tags - they can't be duplicate in generated file.
update: by the way, div tags don't belong to head section

How do I re-render a chart in d3.js using an on click event (dashboard building)?

I’m developing an interactive school report card for a local nonprofit using Bootstrap, PHP, MySQL and d3.js.
I have no problem getting the d3 charts to render (example) once the user has selected a school (3 separate bar charts render onscreen when the user submits the school selection form). I do this by executing queries, encoding them as JSON in PHP/MySQL, then using the PHP include function (on three separate occasions) to reference 3 separate JavaScript files that contain the d3 code that renders the charts. The reference to the data that the d3 is pulling in to populate the graphs is nested inside of PHP tags inside each of these JavaScript files. Again, no issues here, the charts render exactly where they’re supposed to and they look good.
The issue is that I’d like users to be able to be able to change the options on one of the charts and then have that chart re-render with the new data when a button in that form is clicked.
One of the charts that is initially rendered is of 4th grade math test score data from the state standardized test for the selected school. There are other test subjects (English, Science and Social Studies) within the 4th grade that I’d like users to be able to view; additionally, the same 4 subjects are tested in grades 3 and grades 5 – 8. These options for other tests and subjects appear in 2 select boxes that appear in a form located in a div that appears just above the test score graph’s div.
I use Ajax on change event handlers (raw JavaScript) to trigger a MySQL query with the selected options (subject and grade level; school is pulled from a hidden form element which contains the school id for the currently selected school) every time the user’s subject/grade level selection changes. The JSON from the last query is then written into the value of another element that appears in the same form as the subject/grade level select boxes. PHP/html for the form (I'm only using one on change handler in the code below):
echo "<form name='testselect' method=get>";
echo "<table>
<tbody>
<tr>
<td>";
echo "<select name='testtype' id='ttype' onChange='javascript:ajaxFunction();'>";
$dboxquery1 = "SELECT distinct subject FROM leapfile2012 WHERE site_code='$_POST[school]' ORDER BY subject;";
$resultdbq1 = mysql_query($dboxquery1,$con) or die("SQL Error 1: " . mysql_error());
while($dbqr1 = mysql_fetch_array($resultdbq1))
{
echo '<option value="'. $dbqr1['subject'] . '">' . $testType[$dbqr1['subject']] . '</option>';
}
echo "</select>";
echo "</td>
<td>";
echo "<select name='testsub' id='tsub'>";
echo "<option value='ELA' selected='selected'>English</option>";
echo "</select>";
echo "</td>";
echo "<td>" . "<input type='hidden' name='hidden' id='hidename' value='" . $_POST['school'] . "'></input></td>";
echo" <td>";
echo '<input type="button" id="data-submit" value="Get" onClick="javascript:doofus();"></input>';
echo "</td>
<td>
<input type='hidden' name='hidden2' id='hidename2' value=''></input>
</td>
</tr>
</tbody>
</table>";
echo '</form>';
An on click event (user clicks ‘Get’ in the subject/grade level form) then triggers the d3 code that is supposed to repopulate the graph with the test data for the newly selected grade and subject. The JSON for that new/updated graph is pulled from the value of that second hidden element. This is where everything breaks down, I get an error running the following JavaScript/d3:
function doofus() {
var birdmanbirdman = document.getElementById('hidename2').value;
var whutitdo = birdmanbirdman.length;
var quote_be_gone = birdmanbirdman.substring(0,whutitdo);
//var i_hope_this_works = new Array(quote_be_gone);
//alert(i_hope_this_works);
//alert(typeof(i_hope_this_works));
//alert(typeof(birdmanbirdman));
var margin = {top: 35, right: 105, bottom: 30, left: 40},
width = 370 - margin.left - margin.right,
height = 289 - margin.top - margin.bottom;
var data = new Array(quote_be_gone);
//var dontwant = ["site_name","site_code","subject","testsub"];
var formatAsPercentage = d3.format(".1%");
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.rangeRound([height, 0]);
var color = d3.scale.ordinal()
.range(["#3366cc", "#dc3912", "#ff9900", "#109618", "#990099"]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(1);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".0%"))
.tickSize(1);
var svg = d3.select("#area3").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
color.domain(d3.keys(data[0]).filter(function(key)
{ return key !== "year"; }));
data.forEach(function(d) {
var y0 = 0;
d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
d.total = d.ages[d.ages.length - 1].y1;
});
x.domain(data.map(function(d) { return d.year; }));
y.domain([0, d3.max(data, function(d) { return d.total; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.attr("font-size", "1.0em")
.style("text-anchor", "end")
/*.text("Population")*/;
var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function(d) { return "translate(" + x(d.year) + ",0)"; });
state.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.y1); })
.attr("stroke","black")
.attr("stroke-width",0.5)
.attr("height", function(d) { return y(d.y0) - y(d.y1); })
.style("fill", function(d) { return color(d.name); });
state.selectAll("text.one")
.data(function(d) { return d.ages; })
.enter().append("text")
.attr("x", function(d,i) { return x.rangeBand()/2;})
.attr("y", function(d) { /*if ((y(d.y0) - y(d.y1))>=0.05) */ return y(d.y1) + (y(d.y0) - y(d.y1))/2 + 6; })
.text(function (d) { if ((y(d.y0) - y(d.y1))>=0.05) return formatAsPercentage(d.y1 - d.y0);})
.attr("fill", "white")
.attr("font-family", "sans-serif")
.attr("font-weight", "normal")
.attr("text-anchor", "middle")
.attr("font-size", "0.9em");
var legend = svg.selectAll(".legend")
.data(color.domain().slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width + 6)
.attr("width", 12)
.attr("height", 12)
.attr("stroke","black")
.attr("stroke-width", 0.5)
.style("fill", color);
legend.append("text")
.attr("x", width + 100)
.attr("y", 5)
.attr("dy", ".35em")
.style("text-anchor", "end")
.style("font-size", "9px")
.text(function(d) { return d; });
svg.append("text")
.attr("x", (width / 2))
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.style("font-size", "11px")
.style("font-weight", "normal")
/*.text(gtitle)*/;
}
When I inspect in Chrome, I get “Uncaught TypeError: Cannot read property 'length' of undefined” around this piece of code.
data.forEach(function(d) {
var y0 = 0;
d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
d.total = d.ages[d.ages.length - 1].y1;
});
In the debugging process, I’m able to alert out the JSON that’s supposed to populate the graph. I’m then able to strip off opening and closing quotes using native JavaScript functions (the native data type is string), then successfully verify that the new data is indeed an object. The d3 code in the on click script doesn't seem to be recognizing the new data/Object that I'm attempting to pass in.
I’m not sure what to do at this point. I haven’t been able to find a parallel example online.
Any help you could offer would be greatly appreciated. Forgive my wordiness, I wanted to make sure you all understood my issue in detail. If this is an elementary error, please go easy on me. I only started using JavaScript in March, PHP in April, and d3 six weeks ago.

Change image size on click of button in jQuery

I am working on image upload and I need to add functionality for image shapes.
There are buttons for landscape, portrait, square and panoramic. When the user clicks any of these, the div shape will change accordingly.
This is the code for the square shape but when I click on the square shape, it stretches the image. I want to change the shape of the div without stretching the image.
$('#Square').on('click', function(){
var images = $("#uploadedImage");
for(i=0; i<images.length; i++)
images[i].onload = centerImage(images[i]);
function centerImage(img) {
if (img.width > img.height ) {
var y = 160;
var x = img.width/img.height*y;
var marx = (x-y)/2;
img.style.height = y+"px";
img.style.marginLeft = -(marx) + "px";
}
}
});
It's difficult to recreate running example without more generalized code, but your function clearly changes the dimensions of variable img, the image passed in to the function, and not any div or other element besides the image that was clicked. If you want to change a div based on the same HxW test of the image, change the img.* parts of your function to $('#DivYouWant').* and you should get on the right track. Something along the lines of:
function centerImage(img) {
if (img.width > img.height ) {
var y = 160;
var x = img.width/img.height*y;
var marx = (x-y)/2;
$('#DivYouWannaMod').height = y+"px";
$('#DivYouWannaMod').marginLeft = -(marx) + "px";
}
}

Get value with php and mysql in var name[value1,value2,value2]

How I can insert array value in php and mysql from variable Var s1, s2, s3:
$(function () {
var s1 = [100, 200, 300]; //How to Get Value from mysql database
var s2 = [30, 80, 90]; //How to Get Value from mysql database
var s3 = [120, 90, 80]; //How to Get Value from mysql database
// Can specify a custom tick Array.
// Ticks should match up one for each y value (category) in the series.
var ticks = ['2010', '2011', '2012'];
var plot1 = $.jqplot('chart3', [s1, s2, s3], {
// The "seriesDefaults" option is an options object that will
// be applied to all series in the chart.
seriesDefaults: {
shadow: true, // show shadow or not.
renderer: $.jqplot.BarRenderer,
rendererOptions: {
fillToZero: true
}
},
// Custom labels for the series are specified with the "label"
// option on the series option. Here a series option object
// is specified for each series.
series: [
{label: 'Hotel'},
{label: 'Event Regristration'},
{label: 'Airfare'}
],
// Show the legend and put it outside the grid, but inside the
// plot container, shrinking the grid to accomodate the legend.
// A value of "outside" would not shrink the grid and allow
// the legend to overflow the container.
legend: {
show: true,
placement: 'outsideGrid'
},
axes: {
// Use a category axis on the x axis and use our custom ticks.
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
},
// Pad the y axis just a little so bars can get close to, but
// not touch, the grid boundaries. 1.2 is the default padding.
yaxis: {
pad: 1.05,
tickOptions: {
formatString: '$%d'
}
}
},
grid: {
borderColor: '#000', // CSS color spec for border around grid.
borderWidth: 2.0, // pixel width of border around grid.
shadow: true // draw a shadow for grid.
}
});
// Bind a listener to the "jqplotDataClick" event. Here, simply change
// the text of the info3 element to show what series and ponit were
// clicked along with the data for that point.
$('#chart3').bind('jqplotDataClick',
function (ev, seriesIndex, pointIndex, data) {
$('#info3').html('series: ' + seriesIndex + ', point: ' + pointIndex + ', data: ' + data);
});
});
2 ways:
Ajax
Use: $.getJSON ( http://api.jquery.com/jQuery.getJSON/ )
var ses = {};
$.getJSON('page_adress.php', {variable_you_want_to_pass1: 'its value', variable_you_want_to_pass2: 'var 2 value'}, function(data) {
ses = data;
});
In your PHP:
<?php
$passed_var_1 = $_REQUEST['variable_you_want_to_pass1'];
//.... etc
//Here you get your data from mysql, cast it into array
header('Content-type: application/json');
echo json_encode($dbdata);
?>
So basically after request finishes you will have exact array you had in PHP transferred in JavaScript. Have in mind that this technique uses AJAX. If you want to avoid that, you will have to use second technique.
Dynamically Creating JS
Make PHP generate your javascript. In this case you would have in your main page
<script src="js_data.js.php" type="text/javascript"></script>
In your js_data.js.php file:
<?php
header("content-type: application/x-javascript");
$s1 = array(100,200,300);
//....
var s1 = [<?=implode(', ', $s1)?>],
s2 = [<?=implode(', ', $s2)?>],
s3 = [<?=implode(', ', $s3)?>];
?>
First method (w/o ajax & json)(untidy-way)
First fetch the value from database and have it in PHP variable.
Then put html element in page and assign the value to it.
Then use it in javascript using document.getElement method.
// assume that you have got value from database in $valueFrmDB.
$valueFrmDB;
Now, take html element(you might have to take more than one)
<input type="hidden" id="something" name="something" value="echo value of $valueFrmDB here" />;
Then, in javascript
var vfd = document.getElementById('something').value;
convert string to array
Second method(with ajax and json)(simple & correct but must know ajax and json)
Use ajax to fetch the values from database
Then use json to pass that values to javascript
simply you can do this by:
<?php
$query = mysql_query("SELECT * FROM attendence");
$results = array(array());
while($line = mysql_fetch_array($query)){
$results[] = $line;
}
?>
Javascript
<script type="text/javascript">
$(document).ready(function(){
var data = <?php echo json_encode($results); ?>; //array uses here
var plot1 = jQuery.jqplot ('chart1', [data],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
showDataLabels: true}
},
legend: { show:true, location: 'e' }
});
});
</script>

Dynamically set selection of jcrop (not fixed selection)

I am working with a jcrop now I want to do something like here
jQuery(function(){
jQuery(".image_container .a-center h2").html("Upload another picture")
var api;
jQuery('#cropbox').Jcrop({
bgOpacity: 0.5,
bgColor: 'black',
addClass: 'jcrop-dark',
aspectRatio: 320/180,
setSelect:[320,320,180,180],
onSelect: updateCoords,
onChange: updateCoords
},function(){
api = this;
api.setOptions({ bgFade: true });
api.ui.selection.addClass('jcrop-selection');
});
});
and it gives this kinda output on selection
and I want this kind of selection upon
what should I do to get max selection for width.
var ratio = 1.2222222;
var jcrop_api = $.Jcrop('#modal-file-crop-image');
jcrop_api.setOptions({ aspectRatio: ratio });
var dim = jcrop_api.getBounds();
dim should hold an array of the image size
so like [380,180]
i use the following to center the crop area based on aspect ratio
var $img = $("#modal-file-crop-image");
var w = $img.width();
var h = $img.height();
$img.css({"width": w, "height": h})
var ratio = 1.2222222;
var jcrop_api = $.Jcrop('#modal-file-crop-image');
jcrop_api.setOptions({ aspectRatio: ratio });
var dim = jcrop_api.getBounds();
var x = 0, y = 0, x_ = dim[0], y_ = dim[1];
var x_r = (x_ / ratio) - y_;
var y_r = (y_ / ratio) - x_;
if (x_r > 0) {
x = x_r / 2;
}
if (y_r > 0) {
y = y_r / 2;
}
jcrop_api.setSelect([x, y, dim[0], dim[1]]);
in your case you would probably just set y to 0 all the time
You can't.
It seems Like your main Image file is having bigger size the 320x180. You have select area of 320 x 180 which is smaller then your actual Image.
So Here what you can do is.
Calculate Area and set it up in your code. For this, calculate New Height / Width On the bases of Height and Width Of Image; taking other parameter as master. (e.g for your image in question, Master parameter is Width and you can find a new Height which is based on aspect ratio and master parameter.)
Setup area coordinates.
I think this will solve your issue.

Categories