Data is not distributed through out the whole x axis chart.js zoom plugin - chart.js

I am loading data from the file that contain the time stamp and temperature reading.
Difference between two data can be same or some time it can be a month or so.
Can we update the x axis scale so it min and max value matches the data received.
call back function of the zoom plug in is
let timer;
function update_chart({ chart }) {
clearTimeout(timer);
timer = setTimeout(() => {
var { min, max } = chart.scales.x;
// console.log(min);
// console.log(max);
console.log("Min Location: ", chart.scales.x2.min);
console.log("Max Location: ", chart.scales.x2.max);
var file_min = chart.scales.x2.min;
var file_max = chart.scales.x2.max;
file_min = makeCorrection(file_min);
file_max = makeCorrection(file_max);
console.log("Zoom level", chart.getZoomLevel());
var total_sample = (file_max - file_min) / 116;
console.log("Totoal samples: ", total_sample);
var offset = (total_sample / 50) * 116;
offset = makeCorrection(offset);
console.log("Offfset: ", offset);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var x = [], y1 = [], y2 = [], y3 = [], y4 = [], y5 = [], y6 = [], y7 = [], y8 = [], y9 = [], y10 = [];
var tex = this.responseText;
if (tex[0] == ">") {
window.alert(tex);
}
else {
dataray = tex.split('\n');
//console.log(dataray);
dataray.forEach(element => {
dat = element.split(';');
if (dat.length > 5) {
x.push(dat[0]);
y1.push(dat[1]);
y2.push(dat[2]);
y3.push(dat[3]);
y4.push(dat[4]);
y5.push(dat[5]);
y6.push(dat[6]);
y7.push(dat[7]);
y8.push(dat[8]);
y9.push(dat[9]);
y10.push(dat[10]);
}
});
if (x.length > 10)
{
myLineChart.data.labels = x;
myLineChart.data.datasets[0].data = y1;
myLineChart.data.datasets[1].data = y2;
myLineChart.data.datasets[2].data = y3;
myLineChart.data.datasets[3].data = y4;
myLineChart.data.datasets[4].data = y5;
myLineChart.data.datasets[5].data = y6;
myLineChart.data.datasets[6].data = y7;
myLineChart.data.datasets[7].data = y8;
myLineChart.data.datasets[8].data = y9;
myLineChart.data.datasets[9].data = y10;
myLineChart.stop();
myLineChart.update('none');
}
else
{
console.log("Not enoguh data to plot.....");
}
}
}
};
xhttp.open("GET", "/getfile?s=" + file_min + "&e=" + file_max + "&ge=" + offset, true);
xhttp.send();
}, 100);
}
when chart load it looks like this
enter image description here
after zooming in it looks like this
enter image description here

Related

Problem customize the height of column bar

The column bar is too small. And I couldn't adjust their height. The screen shot is attached here: https://prnt.sc/p09hj9.
I have tried all the methods of column series at https://www.amcharts.com/docs/v4/reference/columnseries/.
am4core.ready(function() {
// Create chart instance
var chart = am4core.create("historical_monthly_chart_range", am4charts.XYChart);
// Push data into the charts
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
var series = chart.series.push(new am4charts.LineSeries());
series.name = "Price Range";
valueAxis.title.text = 'Price (S$ psf)';
series.dataFields.dateX = "date";
series.dataFields.openValueY = "min";
series.dataFields.valueY = "max";
series.tooltipText = "{date} \n Maximum: {max} \n Average: {average} \n Minimum: {min} \n Volume: {value}";
// Setting the appearance
series.tooltip.background.cornerRadius = 20;
series.tooltip.background.strokeOpacity = 0;
series.tooltip.pointerOrientation = "vertical";
series.tooltip.label.minWidth = 40;
series.tooltip.label.minHeight = 40;
series.tooltip.label.textAlign = "left";
series.tooltip.label.textValign = "middle";
series.fillOpacity = 0.5;
series.tensionX = 0.8;
series.fill = am4core.color("#697e69");
var series2 = chart.series.push(new am4charts.LineSeries());
series2.name = "Minimum Price";
series2.dataFields.dateX = "date";
series2.dataFields.valueY = "min";
series2.stroke = am4core.color("#697e69");
series2.tensionX = 0.8;
var series_average = chart.series.push(new am4charts.LineSeries());
series_average.name = "Average Price";
series_average.dataFields.valueY = "average";
series_average.dataFields.dateX = "date";
series_average.stroke = am4core.color("#000");
/* Bar chart series */
var barSeries = chart.series.push(new am4charts.ColumnSeries());
barSeries.dataFields.valueY = "value";
barSeries.dataFields.dateX = "date";
barSeries.fill = am4core.color("#000");
barSeries.columns.width = am4core.percent(60);
chart.cursor = new am4charts.XYCursor();
chart.cursor.xAxis = dateAxis;
chart.legend = new am4charts.Legend();
});
There is a bounty on this issue from AM charts however one workaround can be using scrollbar in Y axis like this following:
chart.scrollbarY = new am4core.Scrollbar();
This is not the best solution i agree but you can use it to slightly zoom with the buttons and scale and see
let me know if it works!

Drill down in google charts

I am trying to implement a drill in or drill down in a pie chart. I actually have a working drill down pie chart, however, when I changed the values of the collection, it did not work. I am wondering what went wrong as I completely followed the working code and just replaced its values. The chart simply does not show up and has an error: Uncaught Error: Unknown header type: 17format+en,default+en,ui+en,controls+en,corechart+en.I.js:191. I am not sure though whether this error is related to the problem.
Javascript:
google.load('visualization', '1', {packages: ['corechart', 'controls']});
google.setOnLoadCallback(drawChart1);
var index = 0;
function drawChart1() {
<%
int aku = 0, cdu = 0, ls = 0, ptr = 0, rad = 0, oper = 0;
int aku1 = 0, aku2 = 0, aku3 = 0, aku4 = 0, aku5 = 0;
int cdu1 = 0, cdu2 = 0, cdu3 = 0, cdu4 = 0, cdu5 = 0, cdu6 = 0;
int ls1 = 0, ls2 = 0, ls3 = 0, ls4 = 0, ls5 = 0, ls6 = 0, ls7 = 0, ls8 = 0, ls9 = 0, ls10 = 0;
int ptr1 = 0, ptr2 = 0, ptr3 = 0, ptr4 = 0;
int rad1 = 0, rad2 = 0, rad3 = 0;
int oper1 = 0;
%> //Dummy values
//Main
var main = [
['Artificial Kidney Unit', <%=aku%>],
['Cardiac Diagnostic Unit', <%=cdu%>],
['Laboratory Services', <%=ls%>],
['Physical Therapy and Rehabilitation', <%=ptr%>],
['Radiology', <%=rad%>],
['Operations', <%=oper%>]
];
//Aku
var akuu = [
['Hemodialysis', <%=aku1%>],
['Peritoneal Dialysis', <%=aku2%>],
['Continuous Renal Replacement Therapy', <%=aku3%>],
['Sustained Low Efficient Dialysis', <%=aku4%>],
['Private Dialysis Suite', <%=aku5%>]
];
//Cdu
var cduu = [
['Electrocardiography', <%=cdu1%>],
['Ambulatory Electrocardiography', <%=cdu2%>],
['Exercise Stress Test', <%=cdu3%>],
['2D Echo', <%=cdu4%>],
['Lower Extremity Arterial & Venous Color Duplex Scan', <%=cdu5%>],
['Carotid Artery Duplex Scan', <%=cdu6%>]
];
//Ls
var lss = [
['Hematology', <%=ls1%>],
['Blood Chemistry', <%=ls2%>],
['Immunology and Serology', <%=ls3%>],
['Clinical Microscopy', <%=ls4%>],
['Microbiology', <%=ls5%>],
['Blood Bank and Transfusion Services', <%=ls6%>],
['Drug Testing', <%=ls7%>],
['Parasitology', <%=ls8%>],
['Surgical Pathology', <%=ls9%>],
['Cytopathology', <%=ls10%>]
];
//Ptr
var ptrr = [
['Physical Therapy', <%=ptr1%>],
['Occupational Therapy', <%=ptr2%>],
['Ultrasound Diagnostic Therapy', <%=ptr3%>],
['Orthotics and Prosthetic Evaluation', <%=ptr4%>]
];
//rad
var radd = [
['X-ray', <%=rad1%>],
['Ultrasound', <%=rad2%>],
['CT Scan', <%=rad3%>]
];
//oper
var operr = [
['Surgery', <%=oper1%>]
];
var collection = [];
collection[0] = google.visualization.arrayToDataTable(main);
collection[1] = google.visualization.arrayToDataTable(akuu);
collection[2] = google.visualization.arrayToDataTable(cduu);
collection[3] = google.visualization.arrayToDataTable(lss);
collection[4] = google.visualization.arrayToDataTable(ptrr);
collection[5] = google.visualization.arrayToDataTable(radd);
collection[6] = google.visualization.arrayToDataTable(operr);
var options1 = {
title: 'Departments',
animation: {'duration': 500,
'easing': 'in'},
action: function() {
button.onclick = function() {
recreateDashboard(0);
};
}
};
var chart1 = new google.visualization.PieChart(document.getElementById('chart1'));
google.visualization.events.addListener(chart1, 'select', drillIn);
google.visualization.events.addListener(chart1, 'click', drillOut);
chart1.draw(collection[0], options1);
function drillIn() {
var sel = chart1.getSelection();
var row = chart1.getSelection()[0].row;
options1['title'] = collection[index].getValue(sel[0].row, 0);
if(index === 0) {
if(row === 0) {
index = 1;
}
if(row === 1) {
index = 2;
}
if(row === 2) {
index = 3;
}
if(row === 3) {
index = 4;
}
if(row === 4) {
index = 5;
}
if(row === 5) {
index = 6;
}
}
else if(index === 1 || index === 2 || index === 3 || index === 4 || index === 5 || index === 6) {
options1['title'] = '# of services rendered in <%=year%>';
index = 0;
}
chart1.draw(collection[index], options1);
}
function drillOut(e) {
if(e.targetID === "title") {
if(index !== 0)
index--;
else if(index === 4 || index === 6 || index === 8)
index -= 2;
chart1.draw(collection[index], options1);
}
}
Html:
<div id="chart1">
</div>
I have figured out the mistake. All of these need a title before inputting the values.
Revised code:
//Main
var main = [
['Department', 'Value'],
['Cardiac Diagnostic Unit', <%=cdu%>],
['Laboratory Services', <%=ls%>],
['Physical Therapy and Rehabilitation', <%=ptr%>],
['Radiology', <%=rad%>],
['Operations', <%=oper%>]
];
//Aku
var akuu = [
['Service', 'Value'],
['Hemodialysis', <%=aku1%>],
['Peritoneal Dialysis', <%=aku2%>],
['Continuous Renal Replacement Therapy', <%=aku3%>],
['Sustained Low Efficient Dialysis', <%=aku4%>],
['Private Dialysis Suite', <%=aku5%>]
];
//Cdu
var cduu = [
['Service', 'Value'],
['Electrocardiography', <%=cdu1%>],
['Ambulatory Electrocardiography', <%=cdu2%>],
['Exercise Stress Test', <%=cdu3%>],
['2D Echo', <%=cdu4%>],
['Lower Extremity Arterial & Venous Color Duplex Scan', <%=cdu5%>],
['Carotid Artery Duplex Scan', <%=cdu6%>]
];
//Ls
var lss = [
['Service', 'Value'],
['Hematology', <%=ls1%>],
['Blood Chemistry', <%=ls2%>],
['Immunology and Serology', <%=ls3%>],
['Clinical Microscopy', <%=ls4%>],
['Microbiology', <%=ls5%>],
['Blood Bank and Transfusion Services', <%=ls6%>],
['Drug Testing', <%=ls7%>],
['Parasitology', <%=ls8%>],
['Surgical Pathology', <%=ls9%>],
['Cytopathology', <%=ls10%>]
];
//Ptr
var ptrr = [
['Service', 'Value'],
['Physical Therapy', <%=ptr1%>],
['Occupational Therapy', <%=ptr2%>],
['Ultrasound Diagnostic Therapy', <%=ptr3%>],
['Orthotics and Prosthetic Evaluation', <%=ptr4%>]
];
//rad
var radd = [
['Service', 'Value'],
['X-ray', <%=rad1%>],
['Ultrasound', <%=rad2%>],
['CT Scan', <%=rad3%>]
];
//oper
var operr = [
['Service', 'Value'],
['Surgery', <%=oper1%>]
];

Passing the lat, lng information to the google map script

I've have an index.html file that includes a gogglemap.js file to display a map of users location. Currently I am attempting to add the proper code to the index.html to pass the lat, lng info to the js file.
Here is filler content for the index file to show what I am attempting to do:
<h3><display user city></h3> <---- this needs to display users city and has filler text to show what I am trying to accomplish.
<div id="map"></div>
<script>var lat=12.356;var lng=-19.31;var country="User Country";var city="User City";</script> <----- seems like it is getting the lat/lng somehow before the index page loads and inserting this script into the index file?
Here is the js file code:
var styles = [{yourcustomstyle}]
var myLatlng = { lat: lat, lng: lng };
function initialize() {
var mapOptions = {
zoom: 12,
center: myLatlng,
styles: styles,
panControl: false,
zoomControl: false,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
overviewMapControl: false
};
var map = new google.maps.Map( document.getElementById('map'), mapOptions );
for (var a = 0; a < 6; a++) {
c = Math.random();
c = c * (0 == 1E6 * c % 2 ? 1 : -1);
d = Math.random()
d = d * (0 == 1E6 * d % 2 ? 1 : -1);
c = new google.maps.LatLng( lat + 0.08 * c + 0.052, lng + 0.2 * d + 0.08),
marker = new google.maps.Marker({
map: map,
position: c,
icon: 'marker.png'
});
}
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&callback=initialize';
document.body.appendChild( script );
}
window.onload = loadScript;

jsPlumb connecting raphael element's

I used raphael.js to draw some element's, and now I want to connect them,
how to connect raphael elements with jsplumb ?
For example, in the JSFiddle below : I'm trying to create connections between 2 circles, but I can't, because the circles have no id, my code .
i can't use this :
jsPlumb.connect({source:"id1", target:"id2"})
I finally found a solution to connect raphael elements with jsplumb, I want to thank Mr: # Simon Porritt (jsPlumb creator) for his help: the solution
jsPlumb.ready(function(){
jsPlumb.Defaults.Container = "drawing_board";
// Create a 480 x 640 canvas.
var paper = Raphael('drawing_board');
// of 90 pixels.
var circle1 = paper.circle(140, 110, 90).attr({ fill: '#3D6AA2', stroke: '#000000', 'stroke-width': 8 });
var circle2 = paper.circle(400, 180, 90).attr({ fill: '#3D6AA2', stroke: '#000000', 'stroke-width': 8 });
var rect = paper.rect(50, 280, 90, 70).attr({ fill: '#3D6AA2', stroke: '#000000', 'stroke-width': 8 });
var ellipse = paper.ellipse(300, 420, 90, 70).attr({ fill: '#3D6AA2', stroke: '#000000', 'stroke-width': 8 });
var offsetCalculators = {
"CIRCLE":function(el, parentOffset) {
var cx = parseInt(el.attr("cx"), 10),
cy = parseInt(el.attr("cy"), 10),
r = parseInt(el.attr("r"), 10);
return {
left: parentOffset.left + (cx - r),
top:parentOffset.top + (cy - r)
};
},
"ELLIPSE":function(el, parentOffset) {
var cx = parseInt(el.attr("cx"), 10),
cy = parseInt(el.attr("cy"), 10),
rx = parseInt(el.attr("rx"), 10),
ry = parseInt(el.attr("ry"), 10);
return {
left: parentOffset.left + (cx - rx),
top:parentOffset.top + (cy - ry)
};
},
"RECT":function(el, parentOffset) {
var x = parseInt(el.attr("x"), 10),
y = parseInt(el.attr("y"), 10);
return {
left: parentOffset.left + x,
top:parentOffset.top + y
};
}
};
var sizeCalculators = {
"CIRCLE":function(el) {
var r = parseInt(el.attr("r"), 10);
return [ r * 2, r * 2 ];
},
"ELLIPSE":function(el) {
var rx = parseInt(el.attr("rx"), 10),
ry = parseInt(el.attr("ry"), 10);
return [ rx * 2, ry * 2 ];
},
"RECT":function(el) {
var w = parseInt(el.attr("width"), 10),
h = parseInt(el.attr("height"), 10);
return [ w, h ];
}
};
jsPlumb.CurrentLibrary.getOffset = function(el) {
el = $(el);
var del = el[0], tn = del.tagName.toUpperCase();
if (offsetCalculators[tn]) {
var so = el.parent().offset();
return offsetCalculators[tn](el, so);
}
else
return el.offset();
};
jsPlumb.CurrentLibrary.getSize = function(el) {
el = $(el);
var del = el[0], tn = del.tagName.toUpperCase();
if (sizeCalculators[tn]) {
return sizeCalculators[tn](el);
}
else
return [ el.outerWidth(), el.outerHeight() ];
};
jsPlumb.connect({source:circle1.node, target:circle2.node, anchor:"Center", connector:"Straight"});
jsPlumb.connect({source:circle1.node, target:rect.node, anchors:["Center", "Top"], connector:"Straight"});
jsPlumb.connect({source:circle2.node, target:ellipse.node, anchor:"Center"});
//raphael draggable
var start = function () {
this.ox = this.attr("cx");
this.oy = this.attr("cy");
},
move = function (dx, dy) {
this.attr({cx: this.ox + dx, cy: this.oy + dy});
jsPlumb.repaint(this.node);
},
up = function () { };
paper.set(circle1, circle2).drag(move, start, up); });

Raphael - Drawing shapes with mouse

What would be the best way to draw a rectangle or circle for that matter using your mouse ?
I just started looking at raphael and it seems I should use, drag? Or mousedown and mouseup ?
No sure.
I would use mousedown and mouseup events on your canvas/paper. On mouse down you should store the x and y positions of the mousedown, then on mouseup you should use the current mouse positions to calculate width and height.
Here is an example, bear in mind thought that I am using JQuery to calculate the mouse positions (if this is not available for you, then you should find another way to get the mouse offsets)
//global variables
var mouseDownX = 0;
var mouseDownY = 0;
//register events on document load
paper.mousedown(OnMouseDown);
paper.mouseup(OnMouseUp);
function OnMouseDown(e){
var offset = $("#Canvas").offset();//This is JQuery function
mouseDownX = e.pageX - offset.left;
mouseDownY = e.pageY - offset.top;
}
function OnMouseUp(e){
var offset = $("#Canvas").offset();//This is JQuery function
var upX = e.pageX - offset.left;
var upY = e.pageY - offset.top;
var width = upX - mouseDownX;
var height = upY - mouseDownY;
DrawRectangle(mouseDownX, mouseDownY, width, height);
}
function DrawRectangle(x, y, w, h){
var element = paper.rect(x, y, w, h);
element.attr({
fill: "#FFF",
stroke: "#F00"
});
}
Hope that helps
Here's an updated version of fiddle (mentioned in the other article) that works with Raphael 2+ (no paper events).
This fiddle shows how a rectangle is dynamically drawn while you drag the mouse.
var mouseDownX = 0;
var mouseDownY = 0;
var elemClicked;
var rect;
$(document).ready(function() {
var paper = Raphael("d1", 300, 200);
// start, move, and up are the drag functions
start = function() {
// storing original coordinates
this.ox = this.attr("x");
this.oy = this.attr("y");
this.attr({
opacity: 1
});
if (this.attr("y") < 60 && this.attr("x") < 60) this.attr({
fill: "#000"
});
}, move = function(dx, dy) {
// move will be called with dx and dy
if (this.attr("y") > 200 || this.attr("x") > 300) this.attr({
x: this.ox + dx,
y: this.oy + dy
});
else {
nowX = Math.min(300, this.ox + dx);
nowY = Math.min(200, this.oy + dy);
nowX = Math.max(0, nowX);
nowY = Math.max(0, nowY);
this.attr({
x: nowX,
y: nowY
});
if (this.attr("fill") != "#000") this.attr({
fill: "#000"
});
}
}, up = function() {
// restoring state
this.attr({
opacity: .5
});
if (this.attr("y") < 60 && this.attr("x") < 60) this.attr({
fill: "#AEAEAE"
});
};
function DrawRectangle(x, y, w, h) {
var element = paper.rect(x, y, w, h);
element.attr({
fill: "gray",
opacity: .5,
stroke: "#F00"
});
$(element.node).attr('id', 'rct' + x + y);
console.log(element.attr('x'));
element.drag(move, start, up);
element.click(function(e) {
elemClicked = $(element.node).attr('id');
});
return element;
}
$("#bind").click(function(e) {
$('#d1').unbind('mousedown');
$('#d1').unbind('mousemove');
$('#d1').unbind('mouseup');
$("#d1").mousedown(function(e) {
// Prevent text edit cursor while dragging in webkit browsers
e.originalEvent.preventDefault();
var offset = $("#d1").offset();
mouseDownX = e.pageX - offset.left;
mouseDownY = e.pageY - offset.top;
rect = DrawRectangle(mouseDownX, mouseDownY, 0, 0);
$("#d1").mousemove(function(e) {
var offset = $("#d1").offset();
var upX = e.pageX - offset.left;
var upY = e.pageY - offset.top;
var width = upX - mouseDownX;
var height = upY - mouseDownY;
rect.attr( { "width": width > 0 ? width : 0,
"height": height > 0 ? height : 0 } );
});
});
$("#d1").mouseup(function(e) {
$('#d1').unbind('mousemove');
var BBox = rect.getBBox();
if ( BBox.width == 0 && BBox.height == 0 ) rect.remove();
});
});
$("#unbind").click(function(e) {
$('#d1').unbind('mouseup');
$('#d1').unbind('mousemove');
$('#d1').unbind('mousedown');
});
$("#clr").click(function(e) {
$('#d1').find('rect').each(function(i, obj) {
$(this).remove();
});
});
$("#del").click(function(e) {
$('#' + elemClicked).remove();
});
});
​
I have tried to modify the above fiddle from Miro. Please check my updated version here
var canvas = $('#canvas');
var paper = Raphael(canvas.attr('id'), canvas.width(), canvas.height());
var mouseDownX = 0;
var mouseDownY = 0;
var elemClicked;
var shap;
var borderColor = '#093';
var fillColor = '#eee';
var option = 1;
var shapOpacity = .5;
var ShapType = {RECTANGLE: 1, CIRCLE: 2, LINE: 3}
$(document).ready(function() {
$("#action").change(function() {
option = $('option:selected', this).val();
});
$("#start").click(function(e) {
reset();
$(canvas).mousedown(function(e) {
e.originalEvent.preventDefault();
var offset = $(canvas).offset();
mouseDownX = e.pageX - offset.left;
mouseDownY = e.pageY - offset.top;
if(option == ShapType.RECTANGLE){
shap = drawRectangle(mouseDownX, mouseDownY, 0, 0);
}
else if(option == ShapType.CIRCLE){
shap = drawCircle(mouseDownX, mouseDownY, mouseDownX, mouseDownY);
}else if(option == ShapType.LINE){
shap = drawLine(mouseDownX, mouseDownY, mouseDownX, mouseDownY);
}
$(canvas).mousemove(function(e) {
var offset = $(canvas).offset();
var upX = e.pageX - offset.left;
var upY = e.pageY - offset.top;
var width = upX - mouseDownX;
var height = upY - mouseDownY;
if(option == ShapType.RECTANGLE){
shap.attr( { "width": width > 0 ? width : 0,
"height": height > 0 ? height : 0 } );
}else if(option == ShapType.CIRCLE || option == ShapType.LINE){
shap.updateEnd(upX, upY);
}
}); // end mouse down.
});// end mouse down.
$(canvas).mouseup(function(e) {
$(canvas).unbind('mousemove');
if(option == ShapType.RECTANGLE){
var BBox = shap.getBBox();
if ( BBox.width == 0 && BBox.height == 0 ) shap.remove();
}
}); // end mouse up.
}); // end document ready.
$("#done").click(function(e) {
$(canvas).unbind('mouseup');
$(canvas).unbind('mousemove');
$(canvas).unbind('mousedown');
});
$("#clear").click(function(e) {
$(canvas).find('rect, circle, path').each(function(i, obj) {
$(this).remove();
});
});
$("#deleteshap").click(function(e) {
$('#' + elemClicked).remove();
});
var start = function() {
this.ox = this.attr("x");
this.oy = this.attr("y");
this.attr({
opacity: shapOpacity
});
this.ow = this.attr('width');
this.oh = this.attr('height');
}
var move = function(dx, dy) {
nowX = Math.min(paper.width, this.ox + dx);
nowY = Math.min(paper.height, this.oy + dy);
nowX = Math.max(0, nowX);
nowY = Math.max(0, nowY);
this.attr({
x: nowX,
y: nowY
});
if (this.attr("fill") != fillColor) this.attr({
fill: fillColor
});
}
var up = function() {
this.attr({
opacity: shapOpacity
});
if (this.attr("y") < 60 && this.attr("x") < 60) this.attr({
fill: fillColor
});
};
var reset = function(){
$(canvas).unbind('mousedown');
$(canvas).unbind('mousemove');
$(canvas).unbind('mouseup');
}
function drawLine(startX, startY, endX, endY) {
var start = {
x: startX,
y: startY
};
var end = {
x: endX,
y: endY
};
var getPath = function() {
return "M" + start.x + " " + start.y + " L" + end.x + " " + end.y;
};
var redraw = function() {
node.attr("path", getPath());
node.attr({
stroke: borderColor
});
}
var node = paper.path(getPath());
$(node.node).attr('id', 'shap' + startX + startY);
node.click(function(e) {
elemClicked = $(node.node).attr('id');
});
return {
updateStart: function(x, y) {
start.x = x;
start.y = y;
redraw();
return this;
},
updateEnd: function(x, y) {
end.x = x;
end.y = y;
redraw();
return this;
}
};
};
function drawRectangle(x, y, w, h) {
var element = paper.rect(x, y, w, h);
element.attr({
fill: fillColor,
opacity: shapOpacity,
stroke: borderColor
});
$(element.node).attr('id', 'shap' + x + y);
element.drag(move, start, up);
element.click(function(e) {
elemClicked = $(element.node).attr('id');
});
return element;
}
function drawCircle(x1, y1, x2, y2)
{
var center = {
x: (x1+x2)/2,
y: (y1+y2)/2
};
var radius = {
h: Math.sqrt((y2 - y1) * (y2 - y1))/2,
w: Math.sqrt((x2 - x1) * (x2 - x1))/2
};
var getPath = function () {
return [["M", center.x, center.y], ["m", 0, -radius.h],
["a", radius.w, radius.h, 0, 1, 1, 0, 2 * radius.h],
["a", radius.w, radius.h, 0, 1, 1, 0, -2 * radius.h],
["z"]];
};
var redraw = function () {
node.attr("path", getPath());
node.attr(
{ fill: fillColor,
stroke: borderColor,
});
};
var node = paper.path(getPath());
$(node.node).attr('id', 'shap' + x1 + y1);
node.click(function(e) {
elemClicked = $(node.node).attr('id');
});
dragCircle(node);
return {
updateStart: function (x, y) {
center.x = (x1 + x) / 2;
center.y = (y1 + y) / 2;
radius.w = Math.sqrt((x - x1) * (x - x1))/2;
radius.h = Math.sqrt((y - y1) * (y - y1))/2;
redraw();
return this;
},
updateEnd: function (x, y) {
center.x = (x1 + x) / 2;
center.y = (y1 + y) / 2;
radius.w = Math.sqrt((x - x1) * (x - x1))/2;
radius.h = Math.sqrt((y - y1) * (y - y1))/2;
redraw();
return this;
}
};
} // end circle
dragCircle = function(node) {
var me = node,
lx = 0,
ly = 0,
ox = 0,
oy = 0,
moveFnc = function(dx, dy) {
lx = dx + ox;
ly = dy + oy;
me.transform('t' + lx + ',' + ly);
},
startFun = function() {},
endFnc = function() {
ox = lx;
oy = ly;
};
node.drag(moveFnc, function() {} , endFnc);
};
});
#canvas{background-color:#eee; background-size:cover; width:400px; height:300px;}
.controls input{background: #15A3D7;border: #eee 1px solid;border-radius: 3px;padding: 3px 12px;margin: 5px 3px;color: #fff;}
.controls select{padding: 3px;background: #eee;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="controls">
<input id="start" value="Start" type="button" />
<input id="done" value="Done" type="button" />
<input id="deleteshap" value="Delete Shap" type="button" />
<input id="clear" value="Clear All" type="button" />
<select id="action">
<option value="1">Rectangle</option>
<option value="2">Circle</option>
<option value="3">Line</option>
</select>
</div>
<div class="dvcls" id="canvas"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js"></script>
Here is also a good reference to play with Raphael Js.
http://www.ebooksbucket.com/instant-raphaeljs-starter-b184
Hope this will help.