- How to export canvas to HTML in Fabric.js?
- 1 Answer 1
- How can I make an HTML5 canvas display HTML?
- 2 Answers 2
- Saved searches
- Use saved searches to filter your results more quickly
- License
- niklasvh/html2canvas
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Add canvas to a page with javascript
- 3 Answers 3
How to export canvas to HTML in Fabric.js?
Is there a way to export a canvas element with multiple objects to html with javascript code using fabricjs?I know i can export toJSON or toObject but this isnt HTML. I found that http://canvimation.github.com/ has a function(file>export canvas to html) to export a canvas drawing to native html code.Is that possible with fabricjs?
go to canvimation.github.com and try it.You draw something on canvimation then click file>»export canvas to html» and that opens a new window that shows the drawing in native html code without the canvimation library.
I see! I’ve done a few tricks with canvas exporting recently. What do you want to do with the «html export» once it’s exported: save it, insert it into another web page, etc? Edit: I ask because all that Export as HTML function does in the above example is grab the object and stick it into a new window without the interface decorations. If you want to manipulate the image, or view it locally, you could export it as an SVG.
I want to be able to manipulate some objects fillstyle color.Fabricjs documentation isnt very helpful.I want to create some canvas drawings with something like fabricjs kitchensink and then save the drawing for later manipulation of the color of some of its objects.For example i want to draw a street on kitchensink with trafic lights ,save it somehow and then recall somewhere else and change the color of its traffic lights.
1 Answer 1
Fabric only supports export to (its own) object representation, JSON (basically a serialization of that object representation), and SVG.
If your goal is to create something in fabric, then export it for use in environment that doesn’t support canvas, then maybe you can use SVG — as long as SVG is supported in that environment.
You also have to understand that there’s no such thing as «native html code». There are different versions of HTML — HTML4, HTML5, etc. Canvas is considered to be part of current HTML standard (HTML5). So drawing something on canvas could definitely be considered «using native html code» 😉
If you want recreate fabric rendering without canvas and without SVG then there’s really nothing fabric can help with. It would be unnecessarily complicated to try to provide canvas-less rendering of complex SVG shapes, images (under various transformations, like scaling/rotation), and other objects.
How can I make an HTML5 canvas display HTML?
I realize a canvas cannot directly render HTML. However, it seems like there are potential workarounds. I don’t need the HTML to render perfectly, but I’d like at the very least an image of the rendered HTML. To that end, I attempted to convert the HTML to SVG. This works with very basic html, but breaks with many use cases (such as including images in the html):
var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var img = new Image(); var data = '' var svg = new Blob([data], ); var url = DOMURL.createObjectURL(svg); img.onload = function () < ctx.drawImage(img,0,0,c.width,c.height); DOMURL.revokeObjectURL(url); >img.src = url;
«SVG images aren’t allowed to load any external resources, for example, even ones that appear to be from the same domain.» developer.mozilla.org/en-US/docs/Web/API/Canvas_API/… Try cburgmer.github.io/rasterizeHTML.js
Take a look at dandavis’ link — it works for html with simple styling. If you need something to work in more style intensive pages you can load a headless browser on your server and hand the html+css to the server-browser to create an image. I can recommend PhantomJS: phantomjs.org
2 Answers 2
You could potentially create a basic recursive function to descend into the children of the element that uses a switch or an event handler object to handle certain elements. I demonstrate the former here:
var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.clearRect( 0, 0, canvas.width, canvas.height ); var y = 50; //Set to largest text var offset = 25; (function descend(parent) < for( var i = 0; i < parent.childNodes.length; i++ )< var child = parent.childNodes[i]; var name = child.tagName; var val = child.innerHTML; if( child.hasChildNodes() ) descend(child); switch( name )< case 'H1': ctx.font = "normal 48px Arial"; y += 25; ctx.fillText( val, offset, y ); y += 25; break; case 'H2': ctx.font = "normal 36px Arial"; y += 20; ctx.fillText( val, offset, y ); y += 20; break; case 'H3': ctx.font = "normal 24px Arial"; y += 12; ctx.fillText( val, offset, y ); y += 12; break; default: break; >> >)( canvas );
This code utilizes a function to descend into the element tree of the element and handles certain elements with different rendering techniques. It may seem a little bit excessive, but if you are looking for an effective way to achieve that goal, this method works. Especially with the flexibility of rendering, that being your ability to choose how to render which elements how you want to, so if you want to render all ‘s red for some reason, you can do that. The function I provided is extremely basic, only rendering -, and when you start to mix them around inside the , it gets a little «render jerky». But it demonstrates the concept well, and I think you may find it effective.
Although the thoughts posted in the comments are definitely admirable, if you are looking for flexibility or would rather have control over rendering, this may be the solution you are looking for.
Note: I will say that the code does not detect updates in the element’s DOM; you will need a mutation observer for that. You might also wish to place the code inside of a function that is run when the page is loaded, so that the JavaScript runtime can actually find your element.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Screenshots with JavaScript
License
niklasvh/html2canvas
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
The script allows you to take «screenshots» of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.
The script renders the current page as a canvas image, by reading the DOM and the different styles applied to the elements.
It does not require any rendering from the server, as the whole image is created on the client’s browser. However, as it is heavily dependent on the browser, this library is not suitable to be used in nodejs. It doesn’t magically circumvent any browser content policy restrictions either, so rendering cross-origin content will require a proxy to get the content to the same origin.
The script is still in a very experimental state, so I don’t recommend using it in a production environment nor start building applications with it yet, as there will be still major changes made.
The library should work fine on the following browsers (with Promise polyfill):
As each CSS property needs to be manually built to be supported, there are a number of properties that are not yet supported.
The html2canvas library utilizes Promise s and expects them to be available in the global context. If you wish to support older browsers that do not natively support Promise s, please include a polyfill such as es6-promise before including html2canvas .
To render an element with html2canvas, simply call: html2canvas(element[, options]);
The function returns a Promise containing the element. Simply add a promise fulfillment handler to the promise using then :
html2canvas(document.body).then(function(canvas) < document.body.appendChild(canvas); >);
You can download ready builds here.
$ git clone git://github.com/niklasvh/html2canvas.git
For more information and examples, please visit the homepage or try the test console.
If you wish to contribute to the project, please send the pull requests to the develop branch. Before submitting any changes, try and test that the changes work with all the support browsers. If some CSS property isn’t supported or is incomplete, please create appropriate tests for it as well before submitting any code changes.
About
Screenshots with JavaScript
Add canvas to a page with javascript
I am trying to use Javascript in order to add a canvas to one page which originally does not have one. I am trying to do the following:
var canv=document.createElement("canvas"); canv.setAttribute("id", "canvasID"); alert(canv.id); var c=document.getElementById("canvasID"); alert(c.id);
The problem is the the first alert(canv.id) results in canvasID, while the second alert is undefined because c is null. Can anybody tell me what am I doing wrong? PS: the code is designed to run under Greasemonkey so adding the canvas and its ID in the HTML itself is not a viable option.
You didn’t add canv to the DOM. Additionally, you don’t have to get the canvas by its ID as it’s already referenced in canv .
I was trying to get the canvas by id as some sort of «proof» that the canvas was properly added. What do you mean by «You didn’t add canv to the DOM.» ?
the canvas is just floating in space. It needs to get attached to the DOM, something like document.body.appendChild(canv); , will do the trick.
The DOM is the actual HTML structure of a webpage. You have to add your canvas element to the DOM by using a function like appendChild() . For instance, to add it in a div#myDiv , you can do write the following code: document.getElementById(‘myDiv’).appendChild(canv) .
@Vadzim, I don’t know if you’re in a spree to edit all html5-canvas, but this one is not even related to this tag. Also, if you read the current excerpt of the canvas, you’ll notice it should only be referencing the html5-canvas. Related : this meta-post and this one
3 Answers 3
Use something like Node.appendChild( child ) for adding it to the DOM:
var canv = document.createElement('canvas'); canv.id = 'someId'; document.body.appendChild(canv); // adds the canvas to the body element document.getElementById('someBox').appendChild(canv); // adds the canvas to #someBox
document.body.innerHTML += ' '; // the += means we add this to the inner HTML of body document.getElementById('someBox').innerHTML = ' '; // replaces the inner HTML of #someBox to a canvas
Thank you that did it! Is there a more elegant way to create an element and add an ID? something like document.createElement(‘canvas’,»canvasID»); ??
var canvas = document.getElementById('canvas'); //finds Original Canvas img = document.createElement('img'); img.src = 'images/a.jpg'; //stores image src var canv = document.createElement('canvas'); // creates new canvas element canv.id = 'canvasdummy'; // gives canvas id canv.height = canvas.height; //get original canvas height canv.width = canvas.width; // get original canvas width document.body.appendChild(canv); // adds the canvas to the body element var canvas1 = document.getElementById('canvasdummy'); //find new canvas we created var context = canvas1.getContext('2d'); context.drawImage(img, 0, 0, canvas.width, canvas.height); //draws background image context.drawImage(canvas, 0, 0); //draws original canvas on top of background cscreen = canvas1.toDataURL(); //generates PNG of newly created canvas document.body.removeChild(canv); // removes new canvas
I use this all the time and works great.
Hi, Jeff. Welcome to Stack Overflow. Could you edit your answer to explain why the poster should use your code instead of the code posted in the question (or any of the answers)? There’s a lot of «noise» in your answer dealing with creating and drawing images to the canvas, that has nothing to do with the actual question asked. Also, since this question is old and has an accepted answer, your answer should explain something useful that is not explained in the other answers.
This is the personal answer of Jeff to «how to create a new canvas to extract the image inside a img tag without download it again» but not related with the question. Usually used to get png images or base64 strings to manipulate them. Usually seen on captchas. A quick look here w3schools.com/tags/tryit.asp?filename=tryhtml5_canvas_drawimage