Processing my image for submission (CANVAS) not working - javascript

One quick question. I want to process my canvas into the JotForm Api.
I tried doing it by chart only and it is working. But when doing it on the canvas itself it do not show any data in my JotForm.
This is my code
//Listen for Jotform to get ready
JFCustomWidget.subscribe('ready', function (data) {
//listen for button click
var snapBtn = document.getElementById('snap')
snapBtn.addEventListener('click', () => {
screenshot();
})
// prep data
function prepData(dataURL) {
return {
valid: true,
value: JFCustomWidgetUtils.buildMetadata('imagelinks', [{
'name': "Data from table",
'base64': dataURL
}])
}
}
//process image for form submission
var resultChart, imageData;
var submissionData = {
valid: false,
value: ''
};
// function screenshot() {
// document.querySelectorAll('.chartjs-render-monitor').forEach( chart => { chart.style.display !== 'none' ? resultChart = chart : ''} );
// if(resultChart){
// imageData = resultChart.toDataURL();
// submissionData = prepData( imageData );
// JFCustomWidget.sendData( submissionData );
// }
// }
function screenshot() {
html2canvas(document.body, {
scrollY: -window.scrollY,
crossOrigin: 'Anonymous',
allowTaint: true,
foreignObjectRendering: true,
}).then(function (canvas) {
document.body.appendChild(canvas);
$data0101 = document.body.appendChild(canvas).toDataURL();
document.body.removeChild(canvas);
})
document.querySelectorAll($data0101).forEach
// document.querySelectorAll('.chartjs-render-monitor').forEach( chart => { chart.style.display !== 'none' ? resultChart = chart : ''} );
if (resultChart) {
imageData = $data0101;
submissionData = prepData(imageData);
JFCustomWidget.sendData(submissionData);
}
}
//listen for submit event
JFCustomWidget.subscribe('submit', function () {
JFCustomWidget.sendSubmit(submissionData);
});
});
The working code here is on the part where I commented it.
// function screenshot() {
// document.querySelectorAll('.chartjs-render-monitor').forEach( chart => { chart.style.display !== 'none' ? resultChart = chart : ''} );
// if(resultChart){
// imageData = resultChart.toDataURL();
// submissionData = prepData( imageData );
// JFCustomWidget.sendData( submissionData );
// }
// }
and here,
// document.querySelectorAll('.chartjs-render-monitor').forEach( chart => { chart.style.display !== 'none' ? resultChart = chart : ''} );
I need to get the canvas or the whole HTML itself that is on the actual monitor instead of just the chart I made.
Is there a way I can get my canvas to be inserted inside not the chart. I am lost at this area. Thanks

Related

How to open a file chooser inside a function

I am using quill editor and using a image handler for uploading images and it used to work fine but now i am moving to server side rendering and find this error of "File chooser dialog can only be shown with a user activation." while trying to open the file chooser for uploading the file.
imageHandler() {
//
let self=this
let image;
let image_extension;
var input = document.createElement("input");
// Set its type to file
input.type = "file";
// Set accept to the file types you want the user to select.
// Include both the file extension and the mime type
input.accept = "accept";
// set onchange event to call callback when user has selected file
input.addEventListener("change", onchange)
// dispatch a click event to open the file dialog
input.dispatchEvent(new MouseEvent("click")); //getting the error in this line.
input.onchange = async () => {
//
const file = input.files[0];
var ValidImageTypes = ["image/gif", "image/jpeg", "image/png", "image/jpg", "image/GIF", "image/JPEG", "image/PNG", "image/JPG"];
let file_type = file.type
let filename = file.name
let extension = filename.split('.').pop();
// debugger
if(ValidImageTypes.indexOf(file_type) >= 0){
if(file.size<=500000&&file.size>=50000){
// debugger
var fileToLoad = file
// loadImage(fileToLoad, (canvas) => {
// if(canvas){
// this.setState({
// image=canvas.toDataURL()
// image_extension=extension
// });
this.getBase64(file)
.then(result => {
// debugger
file["base64"] = result;
console.log("File Is",file.base64 );
const res = new Promise(function(resolve, reject) {
axios({
method:'post',
url:API_URL+'api/v1/postblogimage',
headers:{
'x-access-handler':loggedinUser.token
},
data:{
image: file.base64,
image_extension:image_extension,
userid:loggedinUser.userid
}
})
//axios.post(API_URL + 'api/v1/postblogimage', formData, config)
.then((response) => {
if (response.data.error == 'false' || response.data.error == false) {
if (response.data.status == 200 && response.data.message == "Image uploaded successfully") {
//
const range = self.quill.getSelection(true);
// Insert temporary loading placeholder image
// this.quill.insertEmbed(range.index, 'image', `${window.location.origin}/images/loaders/placeholder.gif`);
// Move cursor to right side of image (easier to continue typing)
self.quill.setSelection(range.index + 1);
// Remove placeholder image
self.quill.deleteText(range.index, 1);
// Insert uploaded image
let url=response.data.data[0].imageURL;
self.quill.insertEmbed(range.index, 'image', url);
self.quill.pasteHTML(range.index, <img src={url} class="blog-image-content" alt="Responsive image"/>);
}
}
// else if(response.data.error == 'true' || response.data.status == '500')
// componentProps.error('Sorry, Inappropriate image')
// }
}).catch((error) => {
// reject(Error("It broke"));
});
});
// }
// }, {orientation: true});
// }
})
}
else{
// componentProps.error(" Sorry, File size should be of size between 50 kb to 500kb")
}
}
else{
// this.setState({
// image_warning:'Invalid image type',
// image:'',
// image_extension:''
//})
// this.fileInput.value=''
}
};
}
//render function
<ReactQuill
ref={(el) => this.quillRef = el
}
onChange={this.handleChange}
placeholder={"You can insert images between your blog as well. Max image size to not exceed 500kb.Once you have uploaded an image, just wait, image will show up, if it is approved. Use #hashtags to highlight keywords/impact-terms in your blog, your blog might show up in trending keywords. Example: #gain"}
modules={{
toolbar: {
container: [
[{ header: '1' }, { header: [2,3, 4, 5, 6] }, { font: [] }],
[{ size: [ 'small', false, 'large', 'huge' ] }],
['bold', 'italic', 'underline', 'strike', 'blockquote'],
[{ list: 'ordered' }, { list: 'bullet' }],
['link', 'image', 'video'],
['clean'],
['code-block'],
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'align': [] }],
],
handlers: {
image: this.imageHandler
}
}
}}
/>
Before you click you must add the input to the document body
document.body.appendChild(input);

Browsershot not taking snapshot of chartjs

I'm trying to take screenshot of chartjs library which has an interval set via browsershot and it wouldn't execute javascript code. This is my code. All I'm getting is a blank image.
var canvas = $("#statisticsChart");
var values = canvas.data("data");
var snapshotDone = false;
function snapshot() {
snapshotDone = true;
if (canvas.data("snapshot")) {
var url = chart.toBase64Image();
$("#statisticsChartImage").attr("src", url);
console.log("snapshot");
}
return true;
}
var config = {
type : "line",
data : {
labels : values.labels,
datasets : [
{
label : values.name,
backgroundColor : "rgba(255,99,132,0.2)",
borderColor : "rgba(255,99,132,1)",
borderWidth : 2,
hoverBackgroundColor : "rgba(255,99,132,0.4)",
hoverBorderColor : "rgba(255,99,132,1)",
data : values.values,
}
]
},
option : {
animation : false,
bezierCurve : false,
//onAnimationComplete : snapshot,
}
};
var chart = new Chart(canvas, config);
if (!snapshotDone) {
setTimeout(snapshot, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas
id="statisticsChart"
data-data="{{ json_encode($patient->getChartData()) }}"
data-snapshot="{{ $snapshot ?? false }}"
></canvas>
<img id="statisticsChartImage" />
$shot = Browsershot::html(view("partials.charts.patient-treatments-weightloss-chart", ["patient" => $patient, "snapshot" => true])->render())
->setScreenshotType('jpeg', 100)
->setDelay(3000)
//->screenshot()
->waitForFunction("snapshotDone == true", 1000, 2000)
->save($path. "ad.jpeg")
;
I have added delay so that the function inside for chartjs finishes. I tried using waitForFunction but I'm not sure I get the documentation. Can anyone help?

Ember highcharts shared tooltip

I'm using highcharts plugin, I have about 5 charts on the page. Every chart is a separate component. I'm a new to ember, so I don't know how to make shared tooltip for all charts. I saw examples with jQuery, event on container and one function for all with sync tooltip. I tried to insert those function in component, but it doesn't really work. How it should be done in ember?
This is a mixin:
export default Ember.Mixin.create({
syncExtremes: function (e) {
let thisChart = this.chart;
if (e.trigger !== 'syncExtremes') {
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' });
}
}
});
}
},
sharedRooltips: function () {
Ember.$('#container').bind('mousemove touchmove touchstart', function (e) {
let chart, point, i, event;
for (i = 0; i < Highcharts.charts.length; i = i + 1) {
chart = Highcharts.charts[i];
event = chart.pointer.normalize(e.originalEvent); // Find coordinates within the chart
point = chart.series[0].searchPoint(event, true); // Get the hovered point
if (point) {
point.highlight(e);
}
}
});
Highcharts.Pointer.prototype.reset = function () {
return undefined;
};
Highcharts.Point.prototype.highlight = function (event) {
this.onMouseOver(); // Show the hover marker
this.series.chart.tooltip.refresh(this); // Show the tooltip
this.series.chart.xAxis[0].drawCrosshair(event, this); // Show the crosshair
};
},
In component:
....
this.sharedRooltips();
_syncExtremes= this.syncExtremes;
....
xAxis: {
type: 'datetime',
crosshair: true,
events: {
syncExtremes: _syncExtremes
}
},
....

Dynamically update Google Chart using AngularJS and Java

My goal is to dynamically update the array table for google charts.
I am unable update the content of the Google Chart with the data I'm passing from my Java class. I use tempGraph2 to initialize the graph when the page load but when the user clicks on a file name, the java class passes a formatted string as follows but it is not updating the content of the chart:
[["Domain names","Domain Count"],["Positive-Female",6],["Positive- GenderNeutral",0],["Positive-Male",17],["Neutral-Female",6],["Neutral-GenderNeutral",0],["Neutral-Male",8],["Negative-Female",3],["Negative-GenderNeutral",0],["Negative-Male",19]]
The value is linked using ng-model as follows:
<div ng:model="tempGraph2"
qn:barcolumns="[
{type:'string', name: 'Categories'},
{type:'number', name: 'Counts'}]"
qn:bar="{
legend : {position: 'none'},
chart: { subtitle: 'popularity by percentage' },
chartArea: {height: 400},
backgroundColor: '#F7F7F7'}"></div>
<div ng:model="tempGraph2"
qn:tabcolumns="[
{type:'string', name: 'Categories'},
{type:'number', name: 'Counts'}]"
qn:options="{
backgroundColor: '#F7F7F7'}"></div>
<p> {{tempGraph}}</p>
<p>{{tempGraph2}}</p>
Even using the ng-model, the graph is not being updated but the {{tempGraph2}} output is. Below is the content of the javascript.
Question: Do I need to create something to redraw the graph after I pull in new data or is there another set of logic I need to be using.
app.js:
$scope.tempGraph2 = [['Domain names','Domain Count'],
["placeholder",6],];
$scope.selectJobRow = function(rowIndex) {
$scope.selectedJobRow = rowIndex;
if ($scope.selectedJobRow > -1) {
$scope.showProgress();
$scope.input.job = $scope.input.jobList[rowIndex];
var prepFile = {fileName: $scope.input.job.outputFile, data: "test"}
$http.post("file/graph", prepFile)
.success(function(data, status) {
$scope.input.graphData = data;
$scope.tempGraph2 = $scope.input.graphData.data;
$scope.hideProgress();
$scope.tempGraph = [
['Domain names','Domain Count'],
["Positive-Female",123],
["Positive-GenderNeutral",22],
["Positive-Male",4],
["Neutral-Female",6],
["Neutral-GenderNeutral",76],
["Neutral-Male",8],
["Negative-Female",3],
["Negative-GenderNeutral",98],
["Negative-Male",19]
];
})
.error(function(data, status) {
$scope.hideProgress();
alert("Failed!!!!");
});
}
}
angular.module('charts.table', [
])
.directive('qnOptions', [
function() {
return {
require: '?ngModel',
link: function(scope, element, attr, controller) {
var settings = {
is3D: true
};
var getOptions = function() {
return angular.extend({ }, settings, scope.$eval(attr.qnOptions));
};
// creates instance of datatable and adds columns from settings
var getDataTable = function() {
var columns = scope.$eval(attr.qnTabcolumns);
var data = new google.visualization.DataTable();
angular.forEach(columns, function(column) {
data.addColumn(column.type, column.name);
});
return data;
};
var init = function() {
var options = getOptions();
if (controller) {
var drawChart = function() {
//var data = getDataTable();
// set model
// data.addRows(controller.$viewValue);
var data = new google.visualization.arrayToDataTable(controller.$viewValue);
/*var data = new google.visualization.arrayToDataTable([
['Move', 'Percentage'],
["Positive-Female",6],
["Positive-GenderNeutral",0],
["Positive-Male",17],
["Neutral-Female",6],
["Neutral-GenderNeutral",0],
["Neutral-Male",8],
["Negative-Female",3],
["Negative-GenderNeutral",0]
]); */
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.Table(element[0]);
chart.draw(data);
};
controller.$render = function() {
drawChart();
};
}
if (controller) {
// Force a render to override
controller.$render();
}
};
// Watch for changes to the directives options
scope.$watch(getOptions, init, true);
scope.$watch(getDataTable, init, true);
}
};
}
]);
I can get the table to update from when I toggle between static data but not with dynamic data.

how do you call getJSON inside the highchart section

Currently I am doing this:
$(function () {
// Create the chart
$.getJSON('db_cpu.php', function(data) {
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
enabled: false
},
title: {
text: 'Database utilization'
},
series: data
}, function (chart) {
normalState = new Object();
normalState.stroke_width = null;
normalState.stroke = null;
normalState.fill = null;
normalState.padding = null;
//normalState.r = null;
normalState.style = hash('text-decoration', 'underline');
hoverState = new Object();
hoverState = normalState;
pressedState = new Object();
pressedState = normalState;
//pressedState.style = hash('text-decoration', 'none');
chart_1DButton = chart.renderer.button('1D', 52, 10, function () {
$.getJSON('db_memory.php', function (data) {
console.log(data);
chart.series[0].setData(data);
chart.redraw();
});
unselectButtons();
chart_1DButton.setState(2);
}, normalState, hoverState, pressedState);
chart_1DButton.add();
});
function unselectButtons() {
chart_1DButton.setState(0);
}
});
});
when I clicked on the button, my chart does not diplay any data. dp_cpu.php and db_memory.php outputs json formated data that has name and data in it already. For exmaple dp_cpu.php outputs this data:
[{"name":"ServerA","data":[[1375142940000,1.85],[1375143540000,2.07],[1375144140000,1.96],[1375144740000,1.9],[1375145340000,2.06],[1375145940000,2.03],[1375146540000,1.69],[1375147140000,2.6],[1375147740000,2.1],[1375148340000,1.68],[1375148940000,2.03],[1375149540000,1.83],[1375150140000,1.84],[1375150740000,2.01],[1375151340000,1.88],[1375151940000,1.6],[1375152540000,2.02],[1375153140000,1.27],[1375153740000,1.47],[1375154340000,2],[1375154940000,1.97],[1375155540000,2.51],[1375156140000,3.59],[1375156740000,4.06],[1375157340000,4.13],[1375157940000,4.15],[1375158540000,4.19],[1375159140000,4.13],[1375159740000,4.44],[1375160340000,4.14],[1375160940000,4.15],[1375161540000,5.01],[1375162140000,4.13],[1375162740000,5],[1375163340000,4.97],[1375163940000,5.04],[1375164540000,5.09],[1375165140000,5.14],[1375165740000,4.93],[1375166340000,4.43],[1375166940000,5],[1375167540000,4.93],[1375168140000,5.1],[1375168740000,5.05],[1375169340000,5],[1375169940000,5.12],[1375170540000,4.14],[1375171140000,4.13],[1375171740000,4.85],[1375172340000,4.19],[1375172940000,4.13],[1375173540000,4.17],[1375174140000,2.02],[1375174740000,1.62],[1375175340000,1.77],[1375175940000,2.01],[1375176540000,1.86],[1375177140000,1.85],[1375177740000,2.1],[1375178340000,2.03],[1375178940000,1.79],[1375179540000,2.09],[1375180140000,1.95],[1375180740000,1.73],[1375181340000,2.12],[1375181940000,2.07],[1375182540000,1.65],[1375183140000,2.1],[1375183740000,2.03],[1375184340000,1.63],[1375184940000,2.13],[1375185540000,1.93],[1375186140000,1.65],[1375186740000,2.19],[1375187340000,1.98],[1375187940000,1.69],[1375188540000,2.13],[1375189140000,1.93],[1375189740000,1.72],[1375190340000,2.15],[1375190940000,2.07],[1375191540000,1.7],[1375192140000,2.15],[1375192740000,2.03],[1375193340000,1.73],[1375193940000,2.71],[1375194540000,1.96],[1375195140000,1.72],[1375195740000,2.15],[1375196340000,2.15],[1375196940000,1.85],[1375197540000,2.2],[1375198140000,1.93],[1375198740000,1.8],[1375199340000,2.19],[1375199940000,1.98],[1375200540000,1.85],[1375201140000,2.27]]}]
I have some more info. when I do another getJSON as below example, It looks like I need to reset each series. This is really not convenient. I need to be able to read and external file and just show whatever in that file as chart and redraw the chart. Any ideas?
$.getJSON('db_memory.php', function (data) {
console.log(data);
chart.series[0].setData([[1375142940000,100],[1375143540000,2.07],[1375144140000,1.96],[1375144740000,1.9],[1376408000000,90.06]]);
chart.series[1].setData([[1375142940000,10],[1375143540000,20.07],[1375144140000,40.96],[1375144740000,50.9],[1376408000000,50.06]]);
chart.series[2].setData([[1375142940000,10],[1375143540000,20.07],[1375144140000,40.96],[1375144740000,50.9],[1376408000000,20.06]]);
chart.series[3].setData([[1375142940000,10],[1375143540000,20.07],[1375144140000,40.96],[1375144740000,50.9],[1375145340000,10.06]]);
});
I have tried something like this and it is partially working with one problem. After clicking the button, I get the chart but my button disappears:
$(function () {
// Create the chart
$.getJSON('db_pc.php', function(data) {
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
enabled: false
},
title: {
text: 'Database utilization'
},
series: data
}, function (chart) {
normalState = new Object();
normalState.stroke_width = null;
normalState.stroke = null;
normalState.fill = null;
normalState.padding = null;
//normalState.r = null;
normalState.style = hash('text-decoration', 'underline');
hoverState = new Object();
hoverState = normalState;
pressedState = new Object();
pressedState = normalState;
//pressedState.style = hash('text-decoration', 'none');
chart_1DButton = chart.renderer.button('1D', 52, 10, function () {
$.getJSON('db_memory.php', function (data1) {
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
enabled: false
},
title: {
text: 'Database utilization'
},
series: data1
});
});
unselectButtons();
chart_1DButton.setState(2);
}, normalState, hoverState, pressedState);
chart_1DButton.add();
});
function unselectButtons() {
chart_1DButton.setState(0);
}
});
});
You can use addSeries() then you will not need to reset data, but in case when you use setData, redrawing is called, so redraw() can be skipped.
You only add your button when the chart is created.
The problem is that when you use the following code
, new Highcharts.StockChart..., the chart will load again, so it's will render without your button.
So, you have two options, add a callback that will add the button again, or use serie.setData to change it's data dinamically.
I'd go with the second option.
Other problem is that the response is an array, you have to access it the following way data[0]
Finally will have the following code:
chart_1DButton = chart.renderer.button('1D', 52, 10, function () {
$.getJSON('db_memory.php', function (data) {
// update data
// chart.series[0].setData( data[0].data );
// update series' options
chart.series[0].update(data[0]);
});
unselectButtons();
chart_1DButton.setState(2);
}, normalState, hoverState, pressedState);
after looking at different options, I realized that what I need to do maybe better implemented using html/css type buttons:
https://gist.github.com/kix/3039177
And using jquery click event I can load any kind of chart to the div:
$(document).ready(function(){
$("#prof_d").click(function(){
web_cpu();
});
});

Categories

Resources