Convert html div having multiple images to single image using javascript

前端 未结 3 438
梦如初夏
梦如初夏 2021-01-25 04:53

I am trying to convert a DIV to single image. The div has 4 images in it. I have found the js for \"htmltocanvas\" but this jquery plugin does not create image with all images p

3条回答
  •  天命终不由人
    2021-01-25 05:45

    Here's my attempt:

    http://jsfiddle.net/8FFQM/1/

    Don't worry about those huge codes in the html, they're just the images url-encoded, you don't have to do it if your images are hosted on your domain.

    The exported image as jpg is the one with red boarder (scroll around in the result window):

    var DivsToJPG = function( parent ) {
        this.canvasSizeX = 0;
        this.canvasSizeY = 0;
        this.init = function( parent ) {
            this.images = parent.find('img');
            this.setSizes();
            this.createCanvas();
            this.drawImages();
            this.exportJPG();
        }
    
        this.setSizes = function() {
            for (var i = 0, l = this.images.length; i < l ; i++) {
                var currentImage = this.images.eq(i);
                var posX = currentImage.position().left;
                var width = currentImage.width();
                this.canvasSizeX = this.canvasSizeX > (posX+width) ? this.canvasSizeX : posX + width;
                //console.log(this.canvasSizeX);
                var posY = currentImage.position().top;
                var height = currentImage.height();
                this.canvasSizeY = this.canvasSizeY > (posY+height) ? this.canvasSizeY : posY + height;
    
             }
        }
    
        this.createCanvas = function() {
            this.canvas = document.createElement('canvas');
            this.canvas.id     = "exportCanvas";
            this.canvas.width  = this.canvasSizeX;
            this.canvas.height = this.canvasSizeY;
            this.ctx = this.canvas.getContext("2d");
            document.body.appendChild(this.canvas);
        }
    
        this.drawImages = function() {
            for (var i = 0, l = this.images.length; i < l ; i++) {
                var currentImage = this.images[i];
                var $currentImage = this.images.eq(i);
                this.ctx.drawImage(currentImage, $currentImage.position().left, $currentImage.position().top, $currentImage.width(), $currentImage.height());
            }
        }
    
        this.exportJPG = function() {
            var dataURL = this.canvas.toDataURL();
            this.img = document.createElement('img');
            this.img.id = "createdImage";
            this.img.src     = dataURL;
            document.body.appendChild(this.img);
        }
    
        this.init( parent );
    }
    
    var divsToJPG = new DivsToJPG($('#myJershy'));
    

    PS: it's a bit longer but it should take care of everything, it uses a bit of jQuery

提交回复
热议问题