使用场景
在生成canvas时候需要图片自适应canvas容器的大小
方法一 将图片以背景图方式
<div class="content-img" id="haibaoone" :style="`background: url(`+info.poster_background+`)center center / cover no-repeat;`" > <div class="header_box"> <img :src="info.avatar" crossOrigin="anonymous" /> <div class="header_name" :style="{color:info.poster_user_color}">{{info.name}}</div> </div> <div class="qrcode_img"> <img :src="qrcode"/> </div> </div>
方法二 给图片设置相对div的100%的宽高,再设置object-fit:cover;
<div class="content-img" id="haibaoone"> <img :src="info.poster_background" style="width:100%;height:100%;object-fit:cover;"/> <div class="header_box"> <img :src="info.avatar" crossOrigin="anonymous" /> <div class="header_name" :style="{color:info.poster_user_color}">{{info.name}}</div> </div> <div class="qrcode_img"> <img :src="qrcode"/> </div> </div>
当要生成的html代码中包含img标签,并且设置了object-fit:cover属性后,通过html2canvas生成的图片object-fit:cover属性没有生效,导致生成的图片与通过样式设置的不一样。
解决方法
CanvasRenderer.prototype.renderReplacedElement = function (container, curves, image) { // if (image && container.intrinsicWidth > 0 && container.intrinsicHeight > 0) { // var box = contentBox(container); // var path = calculatePaddingBoxPath(curves); // this.path(path); // this.ctx.save(); // this.ctx.clip(); // this.ctx.drawImage(image, 0, 0, container.intrinsicWidth, container.intrinsicHeight, box.left, box.top, box.width, box.height); // this.ctx.restore(); // } // 上面注释的原来的代码,下面是我们自己修改后的 // Start Custom Code if (image && container.intrinsicWidth > 0 && container.intrinsicHeight > 0) { var box = contentBox(container); var path = calculatePaddingBoxPath(curves); this.path(path); this.ctx.save(); this.ctx.clip(); let newWidth; let newHeight; let newX = box.left; let newY = box.top; if(container.intrinsicWidth / box.width < container.intrinsicHeight / box.height) { newWidth = box.width; newHeight = container.intrinsicHeight * (box.width / container.intrinsicWidth); newY = box.top + (box.height - newHeight) / 2; } else { newWidth = container.intrinsicWidth * (box.height / container.intrinsicHeight); newHeight = box.height; newX = box.left + (box.width - newWidth) / 2; } this.ctx.drawImage(image, 0, 0, container.intrinsicWidth, container.intrinsicHeight, newX, newY, newWidth, newHeight); this.ctx.restore(); } // End Custom Code };