js生成海报以及canvas的使用
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <base href="<?php echo base_url(); ?>"> <title>生成海报</title> <script type="text/javascript" src="js/sys/jquery.min.js"></script> <script type="text/javascript" src="js/plugin/jquery.qrcode.min.js"></script> <script type="text/javascript" src="js/plugin/qrcode.js"></script> </head> <body> <div class="dialog-wrapper-post"> <p class="dialog-tips">长按海报转发,邀请好友助力点亮</p> <div class="share-post"> <div id="qrcode"></div> <div id="h"> <canvas id="myCanvas"></canvas> </div> </div> </div> </body> </html> <style type="text/css"> #myCanvas { margin: 0 auto; width: 375px; height: 550px; } </style> <script type="text/javascript"> createPoster(); function convertCanvasToImage(canvas){ //新Image对象,可以理解为DOM; var image = new Image(); //canvas.toDataURL返回的是一串Base64编码的URL,当然,浏览器自己肯定支持 //指定格式PNG image.src = canvas.toDataURL("image/png"); return image; } // 根据海报背景图和地址合成一张海报图 function createPoster(){ // 二维码访问的地址拼接 let thref = '<?php echo $jurl; ?>'; var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var devicePixelRatio = window.devicePixelRatio || 1, backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1, ratio = devicePixelRatio / backingStoreRatio; jQuery('#qrcode').qrcode({text:thref}); //将转换后的二维码img标签插入到html中 var mycanvas1=document.getElementsByTagName('canvas')[0]; //获取网页中的canvas对象,这里是通过qrcode生成的二维码的canvas //将转换后的二维码img标签插入到html中 var imgewm=convertCanvasToImage(mycanvas1); // 将二维码canvas生成图片 $('#qrcode').html("");//移除已生成的避免重复生成 $('#qrcode img').hide(); var width = document.getElementById("myCanvas").clientWidth; //宽度 var height = document.getElementById("myCanvas").clientHeight; // 高度 canvas.width = width*ratio; canvas.height = height*ratio; //首先画上背景图 var img = new Image(); img.src = '<?php echo $bgImg; ?>'; // 背景图路径 img.width = width; img.height = height; img.crossOrigin="*"; var headpic = new Image(); headpic.src = '<?php echo $headpic; ?>'; headpic.width = 30; headpic.height = 30; headpic.crossOrigin="*"; img.onload = function() { //必须等待图片加载完成 ctx.scale(ratio, ratio); ctx.drawImage(img, 0, 0, width, (height-100)); //绘制背景图像进行拉伸 console.log("
发布时间:2023-09-03,12:33:41
分享海报,前段生成分享二维码以及海报,进行处理。