8

I am using html2canvas in an effort to get a screenshot of a webpage and render it as a thumbnail (well, 400x300, not exactly a thumbnail).

Based on the Screenshot console code, everything works great with the exception of the thumbnail part.

How can I set the image size to 400x300? In firebug I locate the attribute as: <canvas style="width: 973px; height: 2184px;" width="973" height="2184"></canvas>. However, I cannot figure out in my code(below) or in the html2canvas.js where to hardcode the 400x300 parameters.

screenshot.html:

<html>
<head> 
<title>Screenshot</title> 
<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js">
</script>
<![endif]--> 
</head> 
<body> 
<div class=container> </div> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 

<script type="text/javascript" src="js/html2canvas.js"></script> 
<script type="text/javascript">
var date=new Date();
var message,timeoutTimer,timer;
var proxyUrl="http://html2canvas.appspot.com";
function addRow(a,c,d){var b=$("<tr />").appendTo($(a));b.append($("<td />").css("font-weight","bold").text(c)).append($("<td />").text(d))}function throwMessage(b,a){window.clearTimeout(timeoutTimer);timeoutTimer=window.setTimeout(function(){message.fadeOut(function(){message.remove()})},a||2000);$(message).remove();message=$("<div />").html(b).css({margin:0,padding:10,background:"#000",opacity:0.7,position:"fixed",top:10,right:10,fontFamily:"Tahoma",color:"#fff",fontSize:12,borderRadius:12,width:"auto",height:"auto",textAlign:"center",textDecoration:"none"}).hide().fadeIn().appendTo("body")}$(function(){$("#recommended a").click(function(c){c.preventDefault();$("#url").val(this.href);$("button").click()});var a,b;$('input[type="button"]').click(function(){$(a.contentWindow).unbind("load");$(a).contents().find("body").html2canvas({canvasHeight:b.body.scrollHeight,canvasWidth:b.body.scrollWidth,logging:true})});$("#getscreenshot").click(function(d){d.preventDefault();$(this).prop("disabled",true);var c=$("#url").val();$("#content").append($("<img />").attr("src","loading.gif").css("margin-top",40));var f=document.createElement("a");f.href=c;$.ajax({data:{xhr2:false,url:f.href},url:proxyUrl,dataType:"jsonp",success:function(e){a=document.createElement("iframe");$(a).css({visibility:"hidden"}).width($(window).width()/2).height($(window).height()/2);$("#content").append(a);b=a.contentWindow.document;b.open();$(a.contentWindow).load(function(){var g=$(a).contents().find("body"),h={onrendered:function(j){$("#content").empty().append(j);$("#getscreenshot").prop("disabled",false);$("base").attr("href","")},allowTaint:true,taintTest:false,flashcanvas:"src/flashcanvas.min.js"},i=html2canvas(g,h)});$("base").attr("href",f.protocol+"//"+f.hostname+"/"+f.pathname);e=e.replace("<head>","<head><base href='"+f.protocol+"//"+f.hostname+"/"+f.pathname+"'  />");if($("#disablejs").prop("checked")){e=e.replace(/\<script/gi,"<!--<script");e=e.replace(/\<\/script\>/gi,"<\/script>-->")}b.write(e);b.close()}})})});
</script> 

<form class="well form-search"> 
<label for=url>Website URL:</label> 
<input type=url id=url value="http://www.yahoo.com" class="input-medium search-query"/>
<button class=btn id=getscreenshot>Get screenshot!</button> 
</form> 

 <div id=content></div> 

</body> 
</html>

6 Answers 6

23

Based on Mikkos hint the following woked for me

window.html2canvas([$('body')[0]], {
              onrendered: function(canvas) {
                var extra_canvas = document.createElement("canvas");
                extra_canvas.setAttribute('width',70);
                extra_canvas.setAttribute('height',70);
                var ctx = extra_canvas.getContext('2d');
                ctx.drawImage(canvas,0,0,canvas.width, canvas.height,0,0,70,70);
                var dataURL = extra_canvas.toDataURL();
                var img = $(document.createElement('img'));
                img.attr('src', dataURL);
                // insert the thumbnail at the top of the page
                $('body').prepend(img);
              },
            });
1
  • 1
    Hello, your code got me so close to the success, just missing something with the ctx I have an image with unknown width & height. and i want it to fit (keeping its aspect ratio) in lets say 800x500 px But when the image is widther i got an undesire cropped :( Any idea how to setup a properly fit ? thanks in advance Apr 17, 2018 at 7:27
3

You can create additional new <canvas> with thumbnail dimensions and use drawImage() to scale it down on this new <canvas>.

drawImage() can read <canvas> as image source and you may set target width and height.

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images

2

This works great for me...

    html2canvas(document.getElementById("divTextOrig"), { allowTaint: true, 
    scrollX:0, scrollY: -window.scrollY}).then(function(canvas)
    {
        document.getElementById("divText1").appendChild(canvas);
        $('canvas').css("width",txtWidth);
        $('canvas').css("height",txtHeight);                    
    });
1

I have used a similar approach for your problem, partly based on other answers :) Since resizing images is easier if they are actual images, here is my code:

var img = new Image();
img.src = canvas.toDataURL("image/png");
img.width = 500;
document.getElementsByClassName('modal-body')[0].appendChild(img);

canvasis the output of the html2canvas function; then I create an img setting its source with the img data (the base64 encoding of the canvas). the rest is standard good-old-javascript: set the img width, append to the div element ...

0

Well you can get a reference from the canvas context by using the getContext('2d') method, then by assigning the returned context to a variable (for ex. ctx), you can be able to use the context scale method to scale the canvas context to the desired size. As an addition you can define the canvas size using the style attribute and setting the size of style width and height property by dividing the actual image size with the desired thumbnail size. In the last step you put the resulting number in the ctx.scale(width, height); method.

0

found this way unexpactly for me(later i found why its do so). Just add few attributes after position attributes, like this doc.addImage(img, 'JPEG', 20, 20, 200, 250), and two last number gives you the opportunity to resize img.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.