canvas生成海报

虽然之前也做过类似的生成海报的项目,但是这个项目我又网上查找了一下,发现一个插件挺好用的  html2canvas.js

http://html2canvas.hertzen.com/这里可以下载这个插件

用起来很方面

优先引入这个js

<script type="text/javascript" src="js/html2canvas.min.js"></script>
然后需要定义canvas容器,编写你需要生成的html
	<canvas id="myCanvas" width="1125" height="1180" style="display: none;"></canvas>//定义canvas
						
<div class="bigImg" style="display: none;width: 100%;height: auto;position: absolute;left:0;top: 0;z-index:8;overflow-y: auto;"></div>//生成图片展示的地方

<div class="wrap-con" style="width: 100%;z-index:-1;">//需要转换成图片的html
						<img src="images/p901.png" class="p901">
						<div class="people-photo 902" style="margin-top: -0.5rem;">
							<img src="images/photo-zh2.png" class="photo3">
							<img src="images/photo.png" class="photo1">
							<img src="images/photo-zh1.png" class="photo2">
						</div>
						<div class="changeContent"></div>
						<img src="images/erma.png" class="p903">
						<img src="images/p903.png" class="p904">
						<img src="images/p905.png" class="p905" style="margin-bottom:0;position: absolute;
    bottom: 0;">

					</div>

  下面是如何使用js去把html生成图片

 var canvas = document.getElementById("myCanvas");
                                 var _canvas = document.querySelector('.wrap-con');
                                 var w = parseInt(window.getComputedStyle(_canvas).width);
                                 var h = parseInt(window.getComputedStyle(_canvas).height);
//二倍图解决图片模糊 canvas.width = w * 2; canvas.height = h * 2; canvas.style.width = w + "px"; canvas.style.height = h + "px"; var ctx = canvas.getContext("2d"); ctx.scale(2, 2); html2canvas(document.querySelector('.wrap-con'), {canvas: canvas}).then(function (canvas) { //可以直接下载图片到本地 /* document.querySelector(".down").setAttribute('href', canvas.toDataURL());*/ //也可以直接将生成的图片放在img标签内,实现长按保存图片 var url = canvas.toDataURL('image/jpg'); console.log("url",url);这个就是生成的海报图片 var pHtml = "<img src='"+url+"' alt='二维码图片' style='width:100%;opacity: 1;'>"; $(".bigImg").append(pHtml); });

  

 

 


posted @ 2019-04-22 16:53  kingsnowcan  阅读(2125)  评论(0编辑  收藏  举报