I am doing an HTML to pdf conversion with jspdf
Here is my running code...
http://codepen.io/anon/pen/dPZaYN
You can see the output (below) is different from the PDF..There are no borders and alignment.
I am not able to achieve simple layout / alignment , padding/float etc..
This is how it should look (you can also see here my Html code)
http://screencast.com/t/xE6fbJKrA9m
But when i Get the pdf of this from jspdf it looks like this
http://screencast.com/t/z8cizeY9
This is my jspdf Code ..
var doc = $wnd.jsPDF('p', 'pt', 'a4', true);
var source = $('#content').first();
var specialElementHandlers = {
'#bypassme': function (element, renderer) {
return true;
}
};
doc.fromHTML(
htmltest,
{
'elementHandlers': specialElementHandlers
});
doc.save('Test.pdf');
This is my head
<script type="text/javascript" src="jspdf/jspdf.js"></script>
<script type="text/javascript" src="jspdf/FileSaver.js"></script>
<script type="text/javascript" src="jspdf/jspdf.min.js"></script>
<script type="text/javascript" src="jspdf/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="jspdf/libs/adler32cs.js"></script>
<script type="text/javascript" src="jspdf/BlobBuilder.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.addimage.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.standard_fonts_metrics.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.split_text_to_size.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.from_html.js"></script>
jsPDF's html plugin does not support most css. But despair not, here is a work around.
Try it out:
$( 'a' ).hide();
html2canvas( document.body, { onrendered : function( canvas ) { 'use strict';
var pdf = new jsPDF(), border = 10, width = 210-border*2;
pdf.addImage( canvas.toDataURL( 'image/jpeg' , 0.98 ), 'JPEG',
border, border, width, canvas.height*width/canvas.width );
// pdf.save() does not work on StackOverflow because of cross origin restriction
$('a').show()[0].href = pdf.output( 'dataurlstring' );
// IE 11 does not allow datauri pdf, use save() instead
} } );
body{font:12px "Times New Roman",serif;}h1{font-size:24px;line-height:24px;font-weight:bold;margin-top:0;text-align:right;margin-bottom:5px;}#render_me > div > div{float:right}#render_me > div > div > div{border-bottom:1px solid black;border-right:1px solid black;padding:3px; text-align:center}.b_top{border-top:1px solid black;}.f_c_b_left:last-child{border-left:1px solid black;}
PDF<br>(Ctrl+Click me or open me in new window)
<div id="render_me"><div>
<h1>Invoice</h1>
<div><div class="b_top">Invoice #</div><div>00001-2</div></div>
<div class="f_c_b_left"><div class="b_top">Date</div><div>2015-02-05</div></div>
</div></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src='http://parall.ax/parallax/js/jspdf.js'></script>
The idea is, renders the HTML onto a canvas using html2canvas, then put the screenshot into PDF.
This is not perfect, but at least the elements will be in correct positions and alignments.
Drawbacks:
Like jsPDF's HTML renderer, html2canvas understand few CSS. The major difference is that html2canvas can access the layout did by the browser.
The image only have 96dpi, causing low quality.
Result PDF will be relatively big.
For now, this is my best HTML to PDF solution.
To get better result, I will manually build the PDF (without HTML).
I cannot get the pdf link in this example to open in new window or download, as long as it is ran in StackOverflow's Code snippet. If you put the code elsewhere you can call pdf.save like this fiddle: http://jsfiddle.net/xwksc4ku/1
Related
Ok, I have scoured the internet for a solution to this but I can't find anything. I am trying to find a way to save the contents of an iframe as a PDF. I am always running into an issue where the PDF is just blank. It seems that jsPDF is the only way. I'm kind of wondering if the reason this isn't working is because of the fromHTML() function. I'm not sure. If any of you have figured out a solution I would be very appreciative!!
Here is some sample code you can try in an HTML file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript"></script>
<script>
function demoFromHTML() {
var pdf = new jsPDF('p', 'pt', 'letter');
source = $('#frame')[0];
specialElementHandlers = {
'#bypassme': function (element, renderer) {
return true
}
};
margins = {
top: 80,
bottom: 60,
left: 40,
width: 522
};
pdf.fromHTML(
source,
margins.left,
margins.top, {
'width': margins.width,
'elementHandlers': specialElementHandlers
},
function (dispose) {
pdf.save('Test.pdf');
}, margins);
}
</script>
<button onclick="javascript:demoFromHTML();">PDF</button>
<iframe id="frame" src='https://wikipedia.org/wiki/Main_Page' style="width: 75%;height: 75%;"></iframe>
Go through this article : Convert HTML/CSS Content to a Sleek Multiple Page PDF File Using jsPDF JavaScript library. The provided script allows you to convert any HTML element to PDF. I modified the generate() function slightly so that it takes any HTML element id name and export it as PDF file:
generate = function(doc)
{
var pdf = new jsPDF('p', 'pt', 'a4');
pdf.setFontSize(18);
pdf.fromHTML(document.getElementById(doc),
margins.left, // x coord
margins.top,
{
// y coord
width: margins.width// max width of content on PDF
},function(dispose) {
headerFooterFormatting(pdf, pdf.internal.getNumberOfPages());
},
margins);
var iframe = document.createElement('iframe');
iframe.setAttribute('style','position:absolute;right:0; top:0; bottom:0; height:100%; width:650px; padding:20px;');
document.body.appendChild(iframe);
iframe.src = pdf.output('datauristring');
};
It works 100% on Chrome but Im not sure about other browsers.
Try this solution.
<button id="generatePDF">Generate PDF</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$( '#generatePDF' ).click( function()
{
var pdf = new jsPDF('a4');
pdf.text("Some text inside PDF", 10, 10);
$( '#docpdf' ).attr('src', pdf.output('datauristring'));
});
</script>
<iframe id="docpdf" style="background-color:#EEE; height:400px;">
PDF goes here
</iframe>
A wild guess here but I think this has to do with the fact that Iframes from other domains are protected.
Read into 'cross-domain policy', if it's the cause I'm quite sure you can't work around it very easy.
try
var source = window.document.getElementsByTagName(tagName)[0];
instead of
source = $('#frame')[0];
When I'm referencing my JavaScript file to my index.html file (two separate files in the same folder), and I load the html file in a browser, the drawing i made in the javascript file doesnt show in the canvas.
Here is this HTML code:
<!DOCTYPE html>
<html>
<head>
<title>snake</title>
<script language="javascript" type="text/javascript" src="snake.js"></script>
</head>
<body>
<canvas id="dots" height="500" width="500"></canvas>
</body>
</html>
and here is the JavaScript:
function snake() {
var canvas = document.getElementById("dots");
var snakehead = canvas.getContext('2d');
snakehead.beginPath();
snakehead.arc(100, 75, 50, 0, 2 * Math.PI);
snakehead.stroke();
snakehead.fillStyle = "#2776ff";
snakehead.fill();
}
snake();
in JS-fiddle the code works, it looks like this: https://jsfiddle.net/j2ny6gaf/72/
I'm also getting some errors from JSLint.
"Missing use of 'strict' statement, on the var canvas = document.getElementById
"Combine this with the previous var statement var snake = canvasgetcontext
and a ERROR;
"Document is not defined.[no-undef]
Try adding your script inside the head section (script src=“file-name.js” /script) and try adding a canvas size.
Try
window.onload = function snake() {...}
Try using the script tag
<script type="text/javascript" src="snake.js"></script>
Inside the head section.
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
I have a problem about jQuery and javascript code; when I write this jQuery below between </head> and <body>
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j('#page_effect').fadeIn(3000);
});
</script>
and then write javascript code in body tag
<script src="bubbles.js"></script>
<script type="text/javascript">
bubblesMain(new Object({
type : 'linear',
minSpeed : 100,
maxSpeed : 400,
minSize : 30,
maxSize : 55,
num : 100,
colors : new Array('#FF0000','#FFFFFF','#FFCC99', '#FF33CC')
}));
</script>
then jQuery code can work , but javascript code doesn't work. Finally I found that when I resize the browser after the first loading, it's OK to run.
the bubble.js is to automatically create a canvas element and then raises some bubbles with animation inside canvas.
the partly code is on below :
function bubblesMain(obj){
bubbleResize();
bubbles = new bubbleObject(obj);
bubbles.createBubbles();
setInterval(start,1000/60);
};
//WHEN WINDOW HEIGHT IS CHANGED, REMAKE THE CANVAS ELEMENT
window.onresize = function(event) {
bubbleResize();
}
function bubbleResize(){
var height = parseInt(document.getElementById("canvasBubbles").clientHeight);
var width = parseInt(document.getElementById("canvasBubbles").clientWidth);
document.getElementById("canvasBubbles").innerHTML = '<canvas id="canvas" width="'+width+'px" height="'+height+'px"></canvas>';
}
function start(){
var canvas = document.getElementById("canvas");
canvas.width = canvas.width;
bubbles.move();
bubbles.draw();
};
and I have a <div id="canvasBubbles"></div> indise html.
Then after I added the following code into bubbles.js, It's work to run.
window.onload = function(event) {
bubbleResize();
}
I wonder if someone can suggest a smarter solution to this? thank you.
As stated in the other answers, the <script> tags should be the last thing before the </body> tag. See this question.
The problem with where you've put the tags is that the body of the HTML page hasn't loaded and is therefore not available for manipulation. The reason the window.onload and window.onresize work is because they are called later, when the body of the document is available for manipulation with JS.
Given the details provided in your question, you don't need the jQuery.noConflict() statement.
Here is an alternate version of your code that should do the same thing but with a bit more efficiency. Put it at the end of the body element, just before the </body> tag. I haven't tested it since I don't have all the scripts needed (bubbles, etc).
<!-- this goes at the end of your body element, just before the closing tag -->
<script type="text/javascript" src="bubbles.js"></script>
<script type="text/javascript">
$.ready(function(){
var canvasWrap,
canvasElm,
bubbles;
init();
setInterval(update, 1000/60);
window.onresize = resize;
$('#page_effect').fadeIn(3000);
function init(){
canvasWrap = document.getElementById("canvasBubbles");
canvasElm = document.createElement('canvas');
canvasElm.setAttribute('id', 'canvas');
canvasElm.setAttribute('width', canvasWrap.clientWidth);
canvasElm.setAttribute('height', canvasWrap.clientHeight);
canvasWrap.appendChild(canvasElm);
bubbles = new bubbleObject({
type: 'linear',
minSpeed: 100,
maxSpeed: 400,
minSize: 30,
maxSize: 55,
num: 100,
colors: ['#FF0000','#FFFFFF','#FFCC99', '#FF33CC']
});
bubbles.createBubbles();
update(); // you might not need this
}
function resize() {
canvasElm.setAttribute('width', canvasWrap.clientWidth);
canvasElm.setAttribute('height', canvasWrap.clientHeight);
}
function update(){
// canvasElm.width = canvasElm.width; // is this a hack for something?
bubbles.move();
bubbles.draw();
};
});
</script>
You can write all this inside <body>...</body> or inside <head> ... </head>
NOT works between </body> and <head> tag (maybe works for some less formal browser like old IE).
Script tags should always go at the bottom of the page directly before the tag unless the codes needs to be executed before then for some reason.
And as far as I know, the jQuery noConflict() method is only required when you are using two different libraries that both use the dollar sign, aka jQuery and MooTools, on the same page. You can use jQuery and vanilla javascript without having to use noConflict without any problems.
I am using EaselJS and want to allow for backwards compatibility with ExplorerCanvas.
This should be possible using the following code (see here):
createjs.createCanvas = function () { ... return canvas implementation here ... }
However, If I put an alert in this function and run the code, the function is never run.
How do I go about getting this to work?
Edit:
Here is a simplified example of the code I am using:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='/Scripts/jquery-1.7.1.js'></script>
<script src="/Scripts/excanvas/excanvas.compiled.js"></script>
<script src="/Scripts/easeljs/lib/easeljs-0.5.0.min.js"></script>
<script src='/Scripts/core/jquery.mousewheel.js'></script>
<style>
canvas
{
border: 1px solid #ccc;
}
</style>
<script type='text/javascript'>
$(document).ready(function () {
// Variables
var img;
var stage;
var bmp;
// Bindings
$('#load').click(function () { initialize() }); // DELETE
// Functions
function initialize() {
img = new Image();
img.onload = imageLoadedEvent;
img.src = '/Scripts/viewer/June.jpg';
}
function imageLoadedEvent() {
var canvasElement = generateContext('testCanvas', 400, 400);
stage = new createjs.Stage('testCanvas');
bmp = new createjs.Bitmap(img);
stage.autoClear = true;
stage.addChild(bmp);
stage.update();
}
function generateContext(canvasID, width, height) {
var canvasElement = document.createElement('canvas');
if (typeof (G_vmlCanvasManager) != 'undefined')
canvasElement = G_vmlCanvasManager.initElement(canvasElement);
canvasElement.setAttribute("width", width);
canvasElement.setAttribute("height", height);
canvasElement.setAttribute("id", canvasID);
document.getElementById('viewer').appendChild(canvasElement);
}
});
</script>
</head>
<body>
<div id='viewer'>
<button id='load'>load</button>
</div>
</body>
</html>
This example will run in Chrome and IE9 as a native canvas element is created and used. However in IE8 it fails.
I ran across this issue as well, trying to get ExCanvas to play nice with EaselJS. Here is how I got it working. Hope this helps with your image issue.
Get the source code for EaselJS : https://github.com/gskinner/EaselJS.git. This will get all the javascript files separated out into their own parts.
Copy all those files over to a "easel" folder in your project directory.
The order in which the files are loaded is important, so see below on how to do it.
EaselJS has an option to override the createCanvas method, which is required to use ExCanvas with it. This happens after loading the SpriteSheet.js file, and BEFORE loading Graphics.js, DisplayObject.js, Container.js, etc. In the code below, I used jQuery to load the rest of the js files that easelJs needed. This all happens in the $(document).ready() function.
If done correctly, you should see a 700 x 700 canvas with a red line from top left to bottom right in IE (tested in 8).
head>
<!--
Load ExCanvas first, and jquery
-->
<script type='text/javascript' src='./javascript/excanvas.js'></script>
<script type='text/javascript' src='./javascript/jquery-1.8.2.min.js'></script>
<!--
Have to load Easel js files in a certain order, and override the createCanvas
function in order for it to work in < IE9.
-->
<script type='text/javascript' src='./javascript/easel/UID.js'></script>
<script type='text/javascript' src='./javascript/easel/Ticker.js'></script>
<script type='text/javascript' src='./javascript/easel/EventDispatcher.js'></script>
<script type='text/javascript' src='./javascript/easel/MouseEvent.js'></script>
<script type='text/javascript' src='./javascript/easel/Matrix2D.js'></script>
<script type='text/javascript' src='./javascript/easel/Point.js'></script>
<script type='text/javascript' src='./javascript/easel/Rectangle.js'></script>
<script type='text/javascript' src='./javascript/easel/Shadow.js'></script>
<script type='text/javascript' src='./javascript/easel/SpriteSheet.js'></script>
<script type='text/javascript'>
var canvas, stage;
createjs.createCanvas = function () { return getCanvas(); };
function getCanvas() {
// This is needed, otherwise it will keep adding canvases, but it only use the last one it creates.
canvas = document.getElementById("myCanvas");
if (canvas != null) {
document.getElementById("container").removeChild(canvas);
}
canvas = document.createElement("canvas");
document.getElementById("container").appendChild(canvas);
if (typeof (G_vmlCanvasManager) != 'undefined') {
canvas = G_vmlCanvasManager.initElement(canvas);
canvas.setAttribute("height", "700");
canvas.setAttribute("width", "700");
canvas.setAttribute("style", "height:700px; width:700px;");
canvas.setAttribute("id", "myCanvas");
}
return canvas;
}
</script>
<script type="text/javascript">
$(document).ready(function () {
loadOtherScripts();
stage = new createjs.Stage(canvas);
// Draw a red line from top left to bottom right
var line = new createjs.Shape();
line.graphics.clear();
line.graphics.setStrokeStyle(2);
line.graphics.beginStroke("#FF0000");
line.graphics.moveTo(0, 0);
line.graphics.lineTo(700, 700);
stage.addChild(line);
stage.update();
});
function loadOtherScripts() {
var jsAr = new Array(13);
jsAr[0] = './javascript/easel/Graphics.js';
jsAr[1] = './javascript/easel/DisplayObject.js';
jsAr[2] = './javascript/easel/Container.js';
jsAr[3] = './javascript/easel/Stage.js';
jsAr[4] = './javascript/easel/Bitmap.js';
jsAr[5] = './javascript/easel/BitmapAnimation.js';
jsAr[6] = './javascript/easel/Shape.js';
jsAr[7] = './javascript/easel/Text.js';
jsAr[8] = './javascript/easel/SpriteSheetUtils.js';
jsAr[9] = './javascript/easel/SpriteSheetBuilder.js';
jsAr[10] = './javascript/easel/DOMElement.js';
jsAr[11] = './javascript/easel/Filter.js';
jsAr[12] = './javascript/easel/Touch.js';
for (var i = 0; i < jsAr.length; i++) {
var js = jsAr[i];
$.ajax({
async: false,
type: "GET",
url: js,
data: null,
dataType: 'script'
});
}
}
</head>
<body>
<div id="container"></div>
</body>
</html>
You should instantiate the quasi canvas element by making reference to the original canvas source as provided on the project page example:
<head>
<!--[if lt IE 9]><script src="excanvas.js"></script><![endif]-->
</head>
var el = document.createElement('canvas');
G_vmlCanvasManager.initElement(el);
var ctx = el.getContext('2d');
EDIT:
After further investigation i came to the following conclusions!
There are multiple reasons for not being able to include the image into the canvas:
1st probably there is a bug in the excanvas code for not being able to mimic the native canvas features. I used with more success the modified sancha code, which you can obtain here: http://dev.sencha.com/playpen/tm/excanvas-patch/excanvas-modified.js. See live example here: http://jsfiddle.net/aDHKm/ (try it on IE).
2nd before Easeljs initialize the core objects and classes first is searching for the canvas element existence. Because IE < 9 doesn't have implemented the canvas it's obvious that easeljs core graphics API's can not be instantiated. I think these are the two main reasons that your code is not working.
My suggestion is to try to remake the code without the easeljs. I made a fiddle with the necessary modification to show you how can be done without easeljs: http://jsfiddle.net/xdXrw/. I don't know if it's absolute imperative for you to use easeljs, but certainly it has some limitations in terms of IE8 hacked canvas.