Html2Canvas Resize

安稳与你 提交于 2019-12-01 05:18:40
Mikko Ohtamaa

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

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);
              },
            });

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.

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 ...

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!