生成海报

发布于:2021-06-21 05:24:55

生成海报适用于uni-app,H5

步骤一、引入jQuery.js

import $ from '@/static/js/jquery-1.10.2.min.js';

步骤二、编辑想要海报的样式

海报样式需自定义

<!-- #ifdef APP-PLUS || H5 || APP-NVUE-->
<div class="bgpic" id="bp">
	<img :src="bgurl" style="width: 100%;height: 100%;" />
	<div class="top">
		<div class="headphoto">
			<img style="width: 100%;height: 90rpx;" :src="imgurl+ ''+ extension.head" />
		</div>
		<div class="tit2">{{extension.shopname}}</div>
	</div>
	<div class="tit3">
		<u-parse :html="tit3"></u-parse>
	</div>
	<div class="bottom">
		<div class="qrcodes">
			<div class="qrimg">
				<img :src='src' style='width: 120rpx;height: 120rpx;' />
			</div>
		</div>
		<div class="btn">长按扫码关注我</div>
	</div>
</div>
<!-- #endif -->

步骤三、确认海报图生成后如何显示

<!-- #ifdef APP-PLUS || H5 || APP-NVUE-->
    <div id="picshow" class="bgpic">
	<img src="" style='width: 100%;height: 100%;' />
    </div>
    <div id="shading">生成中...</div>
<!-- #endif -->

步骤四、canvas生成海报图

当需要生成海报时,可执行gotoimg()函数。

该函数可将#bp的海报样式生成为图片的形式,之后在#picshow中显示。

gotoimg() {
	$('#shading').show(0);
	$('#bp').show(0);

	var getPixelRatio = function(context) { // 获取设备的PixelRatio
		var backingStore = context.backingStorePixelRatio ||
			context.webkitBackingStorePixelRatio ||
			context.mozBackingStorePixelRatio ||
			context.msBackingStorePixelRatio ||
			context.oBackingStorePixelRatio ||
			context.backingStorePixelRatio || 1;
		return (window.devicePixelRatio || 1) / backingStore;
	};

	var shareContent = $("#bp")[0];

	var width = shareContent.offsetWidth;
	var height = shareContent.offsetHeight;

	var canvas = document.createElement("canvas");
	var context = canvas.getContext('2d');
	var scale = getPixelRatio(context); //将canvas的容器扩大PixelRatio倍,再将画布缩放,将图像放大PixelRatio倍。
	canvas.width = width * scale;
	canvas.height = height * scale;
	canvas.style.width = width + 'px';
	canvas.style.height = height + 'px';
	context.scale(scale, scale);

	var opts = {
		scale: scale,
		canvas: canvas,
		width: width,
		height: height,
		dpi: window.devicePixelRatio
	};

	html2canvas(shareContent, opts).then(function(canvas) {
		context.mozImageSmoothingEnabled = false;
		context.webkitImageSmoothingEnabled = false;
		context.msImageSmoothingEnabled = false;
		context.imageSmoothingEnabled = false;
		var dataUrl = canvas.toDataURL('image/png', 1.0);
		// var dataUrl = canvas.toDataURL('image/png', 1.0).replace("data:image/png;base64,","");
		var newImg = document.createElement("img");
		newImg.src = dataUrl;
		newImg.width = width;
		newImg.height = height;
		$("#picshow img").attr('src', dataUrl);

		$('#bp').hide(0);
		$('#shading').hide(0);
	});
},

步骤五、css样式

海报生成中的样式,需要生成的海报样式需要自定义。

#shading {
    position: fixed;
    left: 0;
    top: 0;
    height: 100vh;
    z-index: 99;
    background-color: rgba(0, 0, 0, 1);
    text-align: center;
    width: 100%;
    font-size: 4vw;
    color: #fff;
    line-height: 100vh;
}


觉得有用请点个赞吧!
0 557