how to render offscreen canvas properly - html

I'm trying to create a basic example of offscreen rendering canvas but I'm error in js "cannot read property of context". actually my idea is to create a demo like I saw in https://yalantis.com/ I want to create my name initial. If there is any better idea to achieve this then please enlighten me.
Thanks here is my basic attempt before the actual implementation :)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Off Screen Canvas</title>
<script>
function createOffscreenCanvas() {
var offScreenCanvas= document.createElement('canvas');
offScreenCanvas.width= '1360px';
offScreenCanvas.height= '400px';
var context= offScreenCanvas.getContext("2d");
context.fillRect(10,10,200,200);
}
function copyToOnScreen(offScreenCanvas) {
var onScreenContext=document.getElementById('onScreen').getContext('2d');
var offScreenContext=offScreenCanvas.getContext('2d');
var image=offScreenCanvas.getImageData(10,10,200,200);
onScreenContext.putImageData(image,0,0);
}
function main() {
copyToOnScreen(createOffscreenCanvas());
}
</script>
<style>
#onScreen {
width:1360px;
height: 400px;
}
</style>
</head>
<body onload="main()">
<canvas id="onScreen"></canvas>
</body>
</html>

You could achieve this in the following way ...
function createOffscreenCanvas() {
var offScreenCanvas = document.createElement('canvas');
offScreenCanvas.width = '1360';
offScreenCanvas.height = '400';
var context = offScreenCanvas.getContext("2d");
context.fillStyle = 'orange'; //set fill color
context.fillRect(10, 10, 200, 200);
return offScreenCanvas; //return canvas element
}
function copyToOnScreen(offScreenCanvas) {
var onScreenContext = document.getElementById('onScreen').getContext('2d');
onScreenContext.drawImage(offScreenCanvas, 0, 0);
}
function main() {
copyToOnScreen(createOffscreenCanvas());
}
canvas {
border: 1px solid black;
}
<body onload="main()">
<canvas id="onScreen" width="1360" height="400"></canvas>
note : never set canvas's width and height using css. instead use the native width and height property of the canvas.

You can try to do that with experimental OffScreenCanvas API. I'm leaving the link here.
So you don't actually need a canvas element attached to DOM with this experimental API, furthermore you can perform your drawing in webworkers, so it will not block the browser's main thread if you're drawing thousands of objects.
const offscreen = new OffscreenCanvas(256, 256);
offscreen.getContext("2d") // or webgl, etc.
Please beware that it's experimental. You can try to check like "OffscreenCanvas" in window and use that, if it's not available, you can fallback to document.createElement("canvas").

Return offScreenCanvas in your function createOffscreenCanvas
function createOffscreenCanvas() {
var offScreenCanvas= document.createElement('canvas');
offScreenCanvas.width= '1360px';
offScreenCanvas.height= '400px';
var context= offScreenCanvas.getContext("2d");
context.fillRect(10,10,200,200);
return offScreenCanvas;
}
Edit
You were getting image date from canvas not context.
function copyToOnScreen(offScreenCanvas) {
var onScreenContext=document.getElementById('onScreen').getContext('2d');
var offScreenContext = offScreenCanvas.getContext('2d');
var image=offScreenContext.getImageData(10,10,200,200);
onScreenContext.putImageData(image,0,0);
}

Related

Download the content of a div (save the div's appearance like an image) [duplicate]

I'm trying to capture a div into an image using html2canvas
I have read some similar question here like
How to upload a screenshot using html2canvas?
create screenshot of web page using html2canvas (unable to initialize properly)
I have tried the code
canvasRecord = $('#div').html2canvas();
dataURL = canvasRecord.toDataURL("image/png");
and the canvasRecord will be undefined after .html2canvas() called
and also this
$('#div').html2canvas({
onrendered: function (canvas) {
var img = canvas.toDataURL()
window.open(img);
}
});
browser gives some (48 to be exact) similar errors like:
GET http://html2canvas.appspot.com/?url=https%3A%2F%2Fmts1.googleapis.com%2Fvt%…%26z%3D12%26s%3DGalileo%26style%3Dapi%257Csmartmaps&callback=html2canvas_1 404 (Not Found)
BTW, I'm using v0.34 and I have added the reference file html2canvas.min.js and jquery.plugin.html2canvas.js
How can I convert the div into canvas in order to capture the image.
EDIT on 26/Mar/2013
I found Joel's example works.
But unfortunately when Google map embedded in my app, there will be errors.
<html>
<head>
<style type="text/css">
div#testdiv
{
height:200px;
width:200px;
background:#222;
}
div#map_canvas
{
height: 500px;
width: 800px;
position: absolute !important;
left: 500px;
top: 0;
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
<script type="text/javascript" src="html2canvas.min.js"></script>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script language="javascript">
$(window).load(function(){
var mapOptions = {
backgroundColor: '#fff',
center: new google.maps.LatLng(1.355, 103.815),
overviewMapControl: true,
overviewMapControlOptions: { opened: false },
mapTypeControl: true,
mapTypeControlOptions: { position: google.maps.ControlPosition.TOP_LEFT, style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
panControlOptions: { position: google.maps.ControlPosition.RIGHT_CENTER },
zoomControlOptions: { position: google.maps.ControlPosition.RIGHT_CENTER },
streetViewControlOptions: { position: google.maps.ControlPosition.RIGHT_CENTER },
disableDoubleClickZoom: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
minZoom: 1,
zoom: 12
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
$('#load').click(function(){
html2canvas($('#testdiv'), {
onrendered: function (canvas) {
var img = canvas.toDataURL("image/png")
window.open(img);
}
});
});
});
</script>
</head>
<body>
<div id="testdiv">
</div>
<div id="map_canvas"></div>
<input type="button" value="Save" id="load"/>
</body>
</html>
I ran into the same type of error you described, but mine was due to the dom not being completely ready to go. I tested with both jQuery pulling the div and also getElementById just to make sure there wasn't something strange with the jQuery selector. Below is an example that works in Chrome:
<html>
<head>
<style type="text/css">
div {
height: 50px;
width: 50px;
background-color: #2C7CC3;
}
</style>
<script type="text/javascript" src="html2canvas.js"></script>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script language="javascript">
$(document).ready(function() {
//var testdiv = document.getElementById("testdiv");
html2canvas($("#testdiv"), {
onrendered: function(canvas) {
// canvas is the final rendered <canvas> element
var myImage = canvas.toDataURL("image/png");
window.open(myImage);
}
});
});
</script>
</head>
<body>
<div id="testdiv">
</div>
</body>
</html>
If you just want to have screenshot of a div, you can do it like this
html2canvas($('#div'), {
onrendered: function(canvas) {
var img = canvas.toDataURL()
window.open(img);
}
});
you can try this code to capture a div When the div is very wide or offset relative to the screen
var div = $("#div")[0];
var rect = div.getBoundingClientRect();
var canvas = document.createElement("canvas");
canvas.width = rect.width;
canvas.height = rect.height;
var ctx = canvas.getContext("2d");
ctx.translate(-rect.left,-rect.top);
html2canvas(div, {
canvas:canvas,
height:rect.height,
width:rect.width,
onrendered: function(canvas) {
var image = canvas.toDataURL("image/png");
var pHtml = "<img src="+image+" />";
$("#parent").append(pHtml);
}
});
10 2022
This question is quite old, but if anyone looking for a clear solution to implement then here it is. This is using Pure JS with html2canvas and FileSaver
I have tested and it works fine.
Capture everything inside a div.
Step 1
Include the scripts in your footer. jQuery is not needed, These two are fine. If you already have these two in your file, watch out for the correct version. I know it's a little thing, but it is important.
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"></script>
Step 2
Basic div. The style attribute is optional. I am using it here to make it look presentable.
<div id="savethegirl" style="background-color:coral;color:white;padding:10px;width:200px;">
I am a Pretty girl 👩
</div>
<button onclick="myfunc()">Save the girl</button>
It should look like this
Step 3
Include this script
function myfunc(){
// if you are using a different 'id' in the div, make sure you replace it here.
var element = document.getElementById("savethegirl");
html2canvas(element).then(function(canvas) {
canvas.toBlob(function(blob) {
window.saveAs(blob, "Heres the Girl.png");
});
});
};
Step 4
Click the button and it should save the file.
Resources
CDN from: https://cdnjs.com/
This is from Carlos Delgado's article (https://ourcodeworld.com/articles/read/415/how-to-create-a-screenshot-of-your-website-with-javascript-using-html2canvas). I simplified it
If this answer is useful.
Hit that up arrow 🠉 It will help others to find it.
I don't know if the answer will be late, but I have used this form.
JS:
function getPDF() {
html2canvas(document.getElementById("toPDF"),{
onrendered:function(canvas){
var img=canvas.toDataURL("image/png");
var doc = new jsPDF('l', 'cm');
doc.addImage(img,'PNG',2,2);
doc.save('reporte.pdf');
}
});
}
HTML:
<div id="toPDF">
#your content...
</div>
<button id="getPDF" type="button" class="btn btn-info" onclick="getPDF()">
Download PDF
</button>
You can get the screenshot of a division and save it easily just using the below snippet. Here I'm used the entire body, you can choose the specific image/div elements just by putting the id/class names.
html2canvas(document.getElementsByClassName("image-div")[0], {
useCORS: true,
}).then(function (canvas) {
var imageURL = canvas.toDataURL("image/png");
let a = document.createElement("a");
a.href = imageURL;
a.download = imageURL;
a.click();
});
It can be easily done using html2canvas, try out the following,
try adding the div inside a html modal and call the model id using a jquery function. In the function you can specify the size (height, width) of the image to be displayed. Using modal is an easy way to capture a html div into an image in a button onclick.
for example have a look at the code sample,
`
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<div class="modal-body">
<p>Some text in the modal.</p>
`
paste the div, which you want to be displayed, inside the model. Hope it will help.
window.open didn't work for me... just a blank page rendered... but I was able to make the png appear on the page by replacing the src attribute of a pre-existing img element created as the target.
$("#btn_screenshot").click(function(){
element_to_png("container", "testhtmltocanvasimg");
});
function element_to_png(srcElementID, targetIMGid){
console.log("element_to_png called for element id " + srcElementID);
html2canvas($("#"+srcElementID)[0]).then( function (canvas) {
var myImage = canvas.toDataURL("image/png");
$("#"+targetIMGid).attr("src", myImage);
console.log("html2canvas completed. png rendered to " + targetIMGid);
});
}
<div id="testhtmltocanvasdiv" class="mt-3">
<img src="" id="testhtmltocanvasimg">
</div>
I can then right-click on the rendered png and "save as". May be just as easy to use the "snipping tool" to capture the element, but html2canvas is an certainly an interesting bit of code!
You should try this (test, works at least in Firefox):
html2canvas(document.body,{
onrendered:function(canvas){
document.body.appendChild(canvas);
}
});
Im running these lines of code to get the full browser screen (only the visible screen, not the hole site):
var w=window, d=document, e=d.documentElement, g=d.getElementsByTagName('body')[0];
var y=w.innerHeight||e.clientHeight||g.clientHeight;
html2canvas(document.body,{
height:y,
onrendered:function(canvas){
var img = canvas.toDataURL();
}
});
More explanations & options here: http://html2canvas.hertzen.com/#/documentation.html

canvas closePath on finger release on iPad

I'm trying to use canvas object on iPad; the user need to draw a free curve with the finger and when he releases the finger the system must close the curve and fill it.
Actually I wrote down the following code but the problem is that it draws but it does not close the path on finger release.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=768px, maximum-scale=1.0" />
<title>sketchpad</title>
<script type="text/javascript" charset="utf-8">
window.addEventListener('load',function(){
// get the canvas element and its context
var canvas = document.getElementById('sketchpad');
var context = canvas.getContext('2d');
var img = new Image();
img.src = 'imp_02.jpg';
context.drawImage(img,0,0,600,600);
var colorPurple = "#cb3594";
context.strokeStyle=colorPurple;
context.lineWidth = 5;
context.fillStyle = "red";
// create a drawer which tracks touch movements
var drawer = {
isDrawing: false,
touchstart: function(coors){
context.beginPath();
context.moveTo(coors.x, coors.y);
this.isDrawing = true;
},
touchmove: function(coors){
if (this.isDrawing) {
context.lineTo(coors.x, coors.y);
context.stroke();
}
},
touchend: function(coors){
if (this.isDrawing) {
context.touchmove(coors);
context.closePath();
this.isDrawing = false;
}
}
};
// create a function to pass touch events and coordinates to drawer
function draw(event){
// get the touch coordinates
var coors = {
x: event.targetTouches[0].pageX,
y: event.targetTouches[0].pageY
};
// pass the coordinates to the appropriate handler
drawer[event.type](coors);
}
// attach the touchstart, touchmove, touchend event listeners.
canvas.addEventListener('touchstart',draw, false);
canvas.addEventListener('touchmove',draw, false);
canvas.addEventListener('touchend',draw, false);
// prevent elastic scrolling
document.body.addEventListener('touchmove',function(event){
event.preventDefault();
},false); // end body.onTouchMove
},false); // end window.onLoad
</script>
<style type="text/css"><!--
body{margin:0;padding:0; font-family:Arial;}
#container{position:relative;}
#sketchpad{ border: 1px solid #000;}
--></style>
</head>
<body>
<div id="container">
<canvas id="sketchpad" width="766" height="944">
Sorry, your browser is not supported.
</canvas>
</div>
</body>
</html>
I don't understand what I missed.
Is there anyone who can help me..... I would appreciate a lot!!
You are fetching the touch end co-ordinates from a wrong array.
event object has one more array called changedTouches where you can find the co-ordinates of the point where the touch ended. These end co-ordinates are not in targetTouches array.
So you need
endCoordX = event.changedTouches[0].pageX;
endCoordY = event.changedTouches[0].pageY;
[modify the above code to fit into your scenario. hope you got the concept.... And seriuosly i too got stuck on the same point in the past and wasted more than an hour to know this fact....]

How to print a canvas element?

I have a canvas element on my page. I draw an image over it and some data that the user entered. On a press of a button I want to send the canvas to printer, to print it on paper. I tried to use this plug-in: jQuery.printElement, like that:
the button code:
PRINT
'print_voucher()' function:
function print_voucher()
{
$("#canvas_voucher").printElement();
}
canvas_voucher is the ID of my canvas element. It printed the page, but didn't print the canvas. I tried to use it like that as well:
$("#canvas_voucher img").printElement();
But that didn't even start the printer.
So how can I do that? How can I print the content of the canvas?
**EDIT**
Here's the code that creates my canvas and tries to create an image with it:
function create_voucher(visitor_name, visitor_identity_num, unique_number)
{
var canvas = $("#canvas_voucher")[0];
if (canvas.getContext)
{
var ctx = canvas.getContext('2d');
// Draw image
var img = new Image();
img.src = 'https://someurl.com/image.jpg';
img.onload = function(){
ctx.drawImage(img,0,0);
ctx.fillStyle="#CCC";
ctx.font="bold 20px Arial";
ctx.fillText(visitor_name, 750, 270);
ctx.fillText(visitor_identity_num, 750, 295);
ctx.font="bold 25px Arial";
ctx.fillText(unique_number, 620, 325);
}
var voucher = canvas.toDataURL("image/png");
$("#voucher_img").attr("src", voucher);
} else {
alert('You need Safari or Firefox 1.5+ to see this.');
}
}
This will convert the canvas to a .png image URL and open it in a new browser window
The Print Dialog is triggered to let the user print the page.
function print_voucher(){
var win=window.open();
win.document.write("<br><img src='"+canvas.toDataURL()+"'/>");
win.print();
win.location.reload();
}
Here is example code:
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.fillStyle="gold";
ctx.strokeStyle="blue";
ctx.lineWidth=5;
ctx.rect(50,50,100,100);
ctx.fill();
ctx.stroke();
function print_voucher(){
var win=window.open();
win.document.write("<br><img src='"+canvas.toDataURL()+"'/>");
win.print();
win.location.reload();
}
$("#printVoucher").click(function(){ print_voucher(); });
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas><br>
<button id="printVoucher">Print</button>
</body>
</html>
Found the problem and fixed it.
Apparently it was a security issue at this line:
img.src = 'https://someurl.com/image.jpg';
Once it was pointing out to a server, it was considered as a potential security threat. So I changed it to:
img.src = 'images/image.jpg';
After that I created a function to make an image from the canvas and called it within the 'img.onload' part:
...
img.onload = function(){
ctx.drawImage(img,0,0);
ctx.fillStyle="#CCC";
ctx.font="bold 20px Arial";
ctx.fillText(visitor_name, 750, 270);
ctx.fillText(visitor_identity_num, 750, 295);
ctx.font="bold 25px Arial";
ctx.fillText(unique_number, 620, 325);
draw_voucher_img();
...
function draw_voucher_img()
{
var canvas = $("#canvas_voucher")[0];
var voucher = canvas.toDataURL();
$("#voucher_img").attr("src", voucher);
}
Now it worked!

mxGraph cell resize and graph layout

I'm having problems with resizing cells and built-in mxGraph layouts.
If I put a cell on canvas, and I try to resize it, even for a pixel, it grows huge, something like 50000px x 30000px, so it streches my whole canvas, and of course it is unusable.
If I load a graph from an xml file from the database, I can resize cells without any problems.
Similar thing happens with the built in layouts. I'd like to use compact tree layout (the reason I like it beacuse it aligns my whole horizontal).
When I draw a graph and try to use that layout, my graph goes wild, also streching to 50000px x 30000 px (example dimensions, but the scroll is so tiny I can barely aim it with the mouse).
If I load a graph from xml from a database, compact tree layout works perfect. But as soon as I add another cell in it, and try to use compact tree layout again, it goes wild, again.
I use absolute positioning for div which holds the canvas, as same as on the example here (http://jgraph.github.io/mxgraph/javascript/examples/editors/workfloweditor.html)
This is my css and html :
<head>
<style type="text/css">
#graphContainer {
background: url('../../resources/jgraph/src/images/grid.gif');
left: 20px;
right: 20px;
top: 65px;
bottom: 20px;
position: absolute;
border: 1px solid #F2F2F2;
white-space: nowrap;
font-family: Arial;
font-size: 8pt;
display: block;
}
</style>
</head>
<body>
<div id="graphContainer"></div>
<script>
$(document).ready(function(){
mc.init(document.getElementById('graphContainer'));
});
</script>
</body>
</html>
And this is my javascript for graph initialization (along with the couple of events, beacuse I'm not sure if they are the problem):
mxConnectionHandler.prototype.connectImage = new mxImage('../../resources/jgraph/src/images/connector.gif', 14, 14);
if (!mxClient.isBrowserSupported()) {
mxUtils.error('Browser is not supported!', 200, false);
} else {
var root = new mxCell();
root.insert(new mxCell());
var model = new mxGraphModel(root);
if (mxClient.IS_QUIRKS)
{
document.body.style.overflow = 'hidden';
new mxDivResizer(graphContainer);
}
var editor = new mxEditor();
editor.setGraphContainer(graphContainer);
editor.readGraphModel(model);
var graph = editor.graph;
graph.setConnectable(true);
new mxRubberband(graph);
/* CODE FOR ADDING THE TOOLBAR, excluded from example */
//code for writing out the node name
graph.convertValueToString = function(cell)
{
if (mxUtils.isNode(cell.value))
{
var outValue = cell.value.getAttribute('nodeName');
if (outValue != null && outValue.length > 0)
{
return outValue;
}
return '';
}
return '';
};
//defining on select event
graph.getSelectionModel().addListener(mxEvent.CHANGE, function(sender, evt)
{
events.cellSelectionChanged(graph, graph.getSelectionCell());
});
//triggering the on select event
events.cellSelectionChanged(graph);
//cells added event
graph.addListener(mxEvent.CELLS_ADDED, function(sender, evt) {
var vertex = evt.getProperties().cells[0];
if(vertex.isVertex()){
var decoder = new mxCodec();
var nodeModel = decoder.decode(vertex.value);
if(nodeModel.type=='node' || nodeModel.type=='branch'){
utils.changeCellAttribute(vertex, 'nodeName', 'Node_' + vertex.id);
}else if(nodeModel.type=='start'){
utils.changeCellAttribute(vertex, 'nodeName', 'START');
}else if(nodeModel.type=='end'){
utils.changeCellAttribute(vertex, 'nodeName', 'END');
}else if(nodeModel.type=='form'){
utils.changeCellAttribute(vertex, 'nodeName', 'Form');
}
}
});
//on connect event
graph.connectionHandler.addListener(mxEvent.CONNECT, function(sender, evt){
var model = graph.getModel();
var edge = evt.getProperty('cell');
var source = model.getTerminal(edge, true);
var target = model.getTerminal(edge, false);
});
}
Any thoughts what the problem might be?
Solution:
Complete graph and cell configuration is loaded from the database (in this example), including the width and height for the cells.
The problem was adding toolbar items for certain cell types, more precise, dropped cell default width and height. As I said we are loading the configuration from the database, it is completely string-ified, so were the width and height.
They both had to be cast to JavaScript Number object for resize and layout to behave properly.

Can't get <canvas> in a <table> to shrink in width

I am having a problem getting the desired layout of canvas elements on a page. I am using a table to do the layout. The desired layout is to have one canvas to the left that is full height and two other canvases to the right, one on top of the other, with a combined height of the left canvas. The two right canvases are of fixed width and height. When the browser window is resized I want the left canvas to resize to take up all the width available (up to the width of the right canvases). I am using window.onresize event to catch the resize events and to resize the left canvas.
The problem I see is that the left cavas will resize correctly when the browser window width gets bigger, but fails to shrink when the browser window width gets smaller! The code is below. What gives? Is there something inherent in canvas that doesn't allow flexible resizing?
I have searched for a answer to this issue with no luck. Hopefully someone here has conquered this and can give me a hand.
Here is sample code:
<!DOCTYPE html>
<html>
<head>
<title>SO Example</title>
<script type="text/javascript">
window.onload = function ()
{
var canvas = document.getElementById("wf1");
canvas.width = canvas.parentNode.clientWidth;
canvas.height = canvas.parentNode.clientHeight;
}
window.onresize = function ()
{
var canvas = document.getElementById("wf1");
canvas.width = canvas.parentNode.clientWidth;
canvas.height = canvas.parentNode.clientHeight;
}
</script>
<style type="text/css">
table
{
border-collapse: collapse;
background-color: #ccc;
}
tr, td
{
padding: 0;
line-height: 0;
width: 100%;
}
</style>
</head>
<body>
<table>
<tr class="slot">
<td>
<canvas id="wf1" class="wfblock" style="background-color:red;"></canvas>
</td>
<td>
<canvas id="pm1" style="background-color: green; width: 200px; height: 84px;"></canvas>
<canvas id="pm2" style="background-color: blue; width: 200px; height: 84px;"></canvas>
</td>
</tr>
</table>
</body>
</html>
Your canvas can be adjusted in both directions : growing and shrinking.
I do that frequently but I found that the only thing that always works (especially when tables are involved) is giving 100% dimensions for both width and height and adjust the container (be it a td or a div) in a classical way.
To avoid problem with viewport dimensions being different from the ones of the canvas, I always add a listener for the resize event.
Using jquery, I usually end up with this kind of class, where an instance of Grapher is created for each canvas :
function Grapher(options) {
this.graphId = options.canvasId;
this.dimChanged = true; // you may remove that if you want (see above)
};
Grapher.prototype.draw = function() {
if (!this._ensureInit()) return;
// makes all the drawing, depending on the state of the application's model
// uses dimChanged to know if the positions and dimensions of drawed objects have
// to be recomputed due to a change in canvas dimensions
}
Grapher.prototype._ensureInit = function() {
if (this.canvas) return true;
var canvas = document.getElementById(this.graphId);
if (!canvas) {
return false;
}
if (!$('#'+this.graphId).is(':visible')) return false;
this.canvas = canvas;
this.context = this.canvas.getContext("2d");
var _this = this;
var setDim = function() {
_this.w = _this.canvas.clientWidth;
_this.h = _this.canvas.clientHeight;
_this.canvas.width = _this.w;
_this.canvas.height = _this.h;
_this.dimChanged = true;
_this.draw(); // calls the function that draws the content
};
setDim();
$(window).resize(setDim);
// other inits (mouse hover, mouse click, etc.)
return true;
};
In your case I would create for example new Grapher({canvasId:'#wf1'}).