Reputation: 6259
I wrote this sctipt that creates an Line Chart on an existing canvas:
var myLineChart = new Chart(ctx).Line(data, options);
And on animation Complete it opens the generated Line Chart-Canvas in a new tab:
var options = { onAnimationComplete: function(){
window.open(canvas.toDataURL());
}}
Here you can test it out: https://jsfiddle.net/ds53js5u/3/
What I try to achieve:
Is to also generate the canvas with Jquery
I replaced:
<canvas id="myChart" width="400" height="400"></canvas>
With:
var canvas = $('<canvas/>', {id: "myChart", width: 400, height: 400});
DEMO: https://jsfiddle.net/ds53js5u/4/
But now It doesn't any more generate the DataUrl and open it in the new window! What do i wrong?
It is important for me that the canvas is never drawn to the document!
THANKS
Upvotes: 1
Views: 98
Reputation: 724
A bit of a hack around to ensure the canvas is never drawn to the element but is displayed on the popup - but it works, and is generating with javascript, not jQuery.
https://jsfiddle.net/btzqqq9v/
HTML
<div id="canvasContainer" style="position:absolute; visibility:hidden"></div>
JAVASCRIPT
var s = '<canvas id="myChart" width="400" height="400"></canvas>';
var div = document.getElementById('canvasContainer');
div.innerHTML = s;
var canvas = div.firstChild;
var ctx = canvas.getContext("2d");
Upvotes: 0
Reputation: 193261
The problem is that you are calling native HTTPCanvasElement methods on jQuery object, which of course fails. You need to fix 2 problems.
Append canvas to body in order to use it. For example, by using appendTo
method.
Use HTMLElement as canvas
variable instead of jQuery collection instance. You can get HTMLElement object from jQuery collection as the first element of this collection ([0]
).
Fixed code would be:
var canvas = $('<canvas/>', {id: "myChart", width: 400, height: 400}).appendTo('body')[0]
var ctx = canvas.getContext("2d");
Demo: https://jsfiddle.net/ds53js5u/5/
Upvotes: 0
Reputation:
Try to use this script:
var canvas = $('<canvas/>', {id: "myChart", width: 400, height: 400});
var ctx = canvas[0].getContext("2d");
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
var options = {onAnimationComplete: function(){
window.open(canvas[0].toDataURL());}}
var myLineChart = new Chart(ctx).Line(data, options);
Upvotes: 0
Reputation: 5196
There is nothing wrong with your element creation syntax. But you are trying to execute a DOM method on a jQuery object. use:
canvas[0].toDataURL(); // => "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAEYklEQ…mqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlACBB1YxAJfjJb2jAAAAAElFTkSuQmCC"
Upvotes: 1