0

I see a lot of tutorials online about using canvas to render images and then rather than having to screenshot, they can just right click and save as...

What I am trying to do is select a specific area of my webpage to turn into an image? It includes HTML elements and images, and takes up 600x315 from 0,0.

The point of this is to take out the step of taking a screenshot and then cropping it because I need a very specific image size of 600x315. I want to be able to just right click on the 600x315 canvas and save it.

This is the code I have so far, but it is not doing anything...

 var capture = function() {
        var root = document.documentElement;
        var canvas = document.getElementById('canvas');
        var context = canvas.getContext('2d');
        var selection = {
            top: 0,
            left: 0,
            width: 600,
            height: 315
        };

        canvas.height = selection.height;
        canvas.width = selection.width;

        context.drawWindow(
            window,
            selection.left,
            selection.top,
            selection.width,
            selection.height,
            'rgb(255, 255, 255)'
        );

        var dataURL = canvas.toDataURL('image/png', '');

        // set canvasImg image src to dataURL
        // so it can be saved as an image
        document.getElementById('canvasImg').src = dataURL;
    };

In my body I have this code

<canvas id="canvas" width="600" height="315" style="display:none;"></canvas>
<img id="canvasImg" alt="">
user3399235
  • 247
  • 1
  • 2
  • 8
  • 1
    +1 to @Loktar for the links to the one practical solution of saving html to canvas and then to an image--html2canvas. I would add that html2canvas does a good job if the CSS is simple and is less accurate if the CSS is more complex. html2canvas also cannot reproduce an image on the page that was loaded from another domain. You may run across answers that use svg+foreignObject to save the page--that solution is now a dead-end and will no longer work given CORS security requirements by modern browsers. – markE Aug 14 '14 at 19:58
  • Ouch, didn't realize that it wont work in newer browsers @markE was kind of a knee jerk reaction since these are pretty common requests. – Loktar Aug 14 '14 at 20:27
  • 1
    @Loktar Just to clarify...your html2canvas suggestion will work. It's the svg+foreignObject solution that is dead. ;-) – markE Aug 14 '14 at 21:01

0 Answers0