canvas生成简易海报
效果如下:
代码如下:
<!DOCTYPE html>
<html lang="en"><head><meta content="text/html; charset=utf-8" http-equiv="Content-Type"><meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><meta content="telephone=no" name="format-detection"><title>demo</title><script type="text/javascript" src="js/jquery-1.7.2.min.js"></script><script type="text/javascript" src="js/echo.min.js"></script><script type="text/javascript" src="js/jquery.nav.js"></script><script type="text/javascript" src="js/round.js"></script><script type="text/javascript" src="js/swiper-3.4.2.jquery.min.js"></script><link rel="stylesheet" href="css/index.css" type="text/css"><link rel="stylesheet" href="css/font.css" type="text/css"><script>(function(doc, win) {try {var docEl = doc.documentElement,resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',ratio = window.devicePixelRatio || 1,clientWidth = docEl.clientWidth,recalc = function() {clientWidth = docEl.clientWidth;//防止clientWdith为0if (!clientWidth) {setTimeout(recalc, 100);return;}win.g_html_font_size = clientWidth / 7.5;win.g_fixed_left = 0;docEl.style.fontSize = win.g_html_font_size + 'px';docEl.setAttribute("data-dpr", ratio);try {fix();horizontal();} catch (e) {}},fix = function() {//部分安卓机型中适配会出现问题var ua = navigator.userAgent;var isIOS = /(iPhone|iPad|iPod)/.test(ua);// 非苹果设备,均进行检测if (!isIOS) {if (!win.getComputedStyle) {console.log("getComputedStyle not support")return}var div = win.document.createElement('div');div.style.width = '7.5rem';win.document.body.appendChild(div);var getWidth = parseFloat(win.getComputedStyle(div).width);console.log("divWidth", getWidth);if (getWidth !== clientWidth) {console.log("div is not full screen,fix start");// 此时是出问题的情况var ratio = getWidth / clientWidth;console.log("ratio", ratio);win.g_html_font_size = (win.g_html_font_size / ratio).toFixed(4);docEl.style.fontSize = win.g_html_font_size + 'px';console.log("g_html_font_size", win.g_html_font_size);}div.remove();}},horizontal = function() {//如果是横屏,则缩小界面,尽可能显示更多UI.->将页面内容宽度设置为480像素 (7.5REM X 64 =480 PX)//IPAD竖屏的宽高比是0.75 ,横屏1.333if (window.innerWidth >= 480 && window.innerWidth / window.innerHeight > 0.74) {console.log('horizontal')win.g_html_font_size = 64;docEl.style.fontSize = '64px';console.log("g_html_font_size", win.g_html_font_size);//计算一个fixed元素的左偏移量,因为fixed元素以body为参照,而不以app为参照window.g_fixed_left = (document.body.clientWidth - 480) / 2 / 64; //单位remconsole.log('g_fixed_left', window.g_fixed_left)// console.log('SCROLL WIDTH',window.innerWidth - document.body.clientWidth)//注PC 中由于有滚动条 页面宽度比实际小17px,这里不考虑}}recalc();if (!win.addEventListener) {setTimeout(recalc, 1000);}win.addEventListener(resizeEvt, recalc, false);win.addEventListener('DOMContentLoaded', recalc, false);} catch (e) {console.error(e.message)}})(document, window);/*** 处理iOS 键盘收起页面未下移bug*/(/iphone|ipod|ipad/i.test(navigator.appVersion)) && document.addEventListener('blur', function(e) {// 这里加了个类型判断,因为a等元素也会触发blur事件if (['input', 'textarea'].indexOf(e.target.localName) >= 0 && window) {// console.log('blur',document.body.scrollTop)// document.body.scrollTop = document.body.scrollTop + 1// console.log('blur',document.body.scrollTop)window.scrollTo(window.scrollX, window.scrollY + 1);console.log('blur', window.scrollY)}}, true)</script>
</head><body><div id="start" class="shengcheng">canvas转图片点这</div><div class="box">canvas转图片,图片在这显示:</div><!-- <a className='download-btn' href="" download='海报.jpg'>下载海报</a> --><div class="canvas-con"><canvas id="myCanvas" height="360"></canvas></div>
</body>
<script>$(function () {var cWidth = $(".canvas-con").innerWidth()$('#myCanvas').attr("width",cWidth-20)createCanvas()});function createCanvas() {// alert('生成')// 第一步:创建实例var canvasBox = document.getElementById('myCanvas')var context = canvasBox.getContext("2d");// 添加背景var imgBg = new Image(); imgBg.src = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Ff6567e92b8268b5c6a49c8443756216fa228f56e7c3b-Lv2rxF_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1627114786&t=4f872b6305f5da13ca46c1c3cca780c9';imgBg.setAttribute('crossOrigin', 'anonymous')imgBg.onload = function(){let imgWidth = imgBg.width;let imgHeight = imgBg.height;let scale = 1;let tt = $(".canvas-con").innerWidth();if(imgHeight > tt || imgWidth >tt) {if(imgWidth > imgHeight) {scale = tt/imgWidth*2;}else {scale = tt/imgHeight*2;}}let canvasHeight2 = imgHeight*scale;let canvasWidth2 = imgWidth*scale;context.drawImage(imgBg,0,0,canvasWidth2,canvasHeight2);// 第二步:画圆var img = new Image();img.src = 'https://thirdwx.qlogo.cn/mmopen/vi_32/xuTG1xT83ZicFjINud2O6aN1ECdtoOd2mE89DahRfat22a6d6WQMJYePEjVYxcZY7K0s94zulRhr9ficSe26KuFA/132'; // 首先是先画一个圆形,因为现在我们不是画圆角矩形,所以就不用“张鑫旭”画圆的做法,我们直接使用 `arc` 接口img.setAttribute('crossOrigin', 'anonymous')img.onload = function () {context.save();//(圆的中心的 x 坐标、圆的中心的 y 坐标、圆的半径、起始角、结束角)context.arc(25, 25,25, 0, 2 * Math.PI); // 从画布上裁剪出这个圆形context.clip();//要使用的图像、开始剪切的 x 坐标位置、开始剪切的 y 坐标位置、被剪切图像的宽度、被剪切图像的高度context.drawImage(img, 0, 0, 50, 50);context.restore();}context.fillStyle = '#333333';context.font="16px Arial";// 在画布上输出的文本、开始绘制文本的 x 坐标位置(相对于画布)、开始绘制文本的 y 坐标位置(相对于画布)context.fillText("唐小亭",60,24);context.fillStyle = '#ff0000';context.font="10px Arial";// 在画布上输出的文本、开始绘制文本的 x 坐标位置(相对于画布)、开始绘制文本的 y 坐标位置(相对于画布)context.fillText("这是描述这是描述这是描述",60,44);context.fillStyle = '#333333';context.font="10px Arial";context.lineWidth=1;var str = "这是要换行的长描述这是要换行的长描述这是要换行的长描述这是要换行的长描述这是要换行的长描述这是要换行的长描述这是要换行的长描述这是要换行的长描述这是要换行的长描述这是要换行的长描述这是要换行的长描述这是要换行的长描述。"var lineWidth = 0;var canvasWidth = canvasBox.width;//计算canvas的宽度var initHeight=74;//绘制字体距离canvas顶部初始的高度var lastSubStrIndex= 0; //每次开始截取的字符串的索引var lineNum = 0; // 行数var EllipsisLine = 2// 超出n行省略for(let i=0;i<str.length;i++){lineWidth+=context.measureText(str[i]).width; if(lineWidth>canvasWidth){if (lineNum<EllipsisLine) {// console.log('没有超出')if (lineNum==(EllipsisLine-1)) {context.fillText(str.substring(lastSubStrIndex,(i-2))+'...',0,initHeight);//绘制截取部分} else {context.fillText(str.substring(lastSubStrIndex,i),0,initHeight);//绘制截取部分}initHeight+=15;//40为字体的高度lineWidth=0;lastSubStrIndex=i;lineNum++} else {// console.log('超出了')}// console.log('111',lineWidth,lineNum)}if(i==str.length-1){//绘制剩余部分if (lineNum<EllipsisLine) { lineNum++context.fillText(str.substring(lastSubStrIndex,i+1),0,initHeight);}}}// 添加二维码var codeImg = new Image(); codeImg.src = 'https://img1.baidu.com/it/u=2877499757,3239316825&fm=224&fmt=auto&gp=0.jpg';codeImg.setAttribute('crossOrigin', 'anonymous')codeImg.onload = function(){context.drawImage(codeImg,($(".canvas-con").innerWidth()/2)-110,130,200,200);}}}$(".shengcheng").on("click",function(){// canvas转换成图片var canvasBox = document.getElementById('myCanvas')var canvasToImage = new Image();canvasToImage.src = canvasBox.toDataURL("image/png");$('.box').append(canvasToImage);// 图片下载var img2 = $('.box').children('img').attr("src");var alink = document.createElement("a");alink.href = img2;alink.download = "海报.png";alink.click();})
</script>
</html>
存在的问题:
1.转成图片之后头像不显示了
解决方案:
//设置图片跨域访问//img.setAttribute('crossOrigin', 'anonymous');
canvas生成简易海报相关推荐
- 微信小程序使用canvas生成分享海报功能复盘
前言 近期需要开发一个微信小程序生成海报分享的功能.在h5一般都会直接采用 html2canvas 或者 dom2image 之类的库直接处理.但是由于小程序不具备传统意义的dom元素,所以也没有办法 ...
- 微信网页内使用canvas生成个性化海报
微信网页内使用canvas生成个性化海报 前言 需求 解决方案 1.使用html2canvas插件 2.将微信头像转成base64再插进即将画成canvas的dom结构里面 前言 近期一直在做微信内H ...
- 小程序Canvas生成分享海报避坑指南
关于小程序使用Canvas画布生成分享海报,网上有很多的教程,但是结合到自己的业务上面就BUG百出了 接下来分享一下我的经历 微信出了新的api 微信公众平台目前更新不是太即使,查问题好多帖子都是一两 ...
- uniapp微信小程序canvas生成简单海报并下载
今天项目接到个任务,就是手写canvas海报,并能下载图片.百度了很多海报组件,都不尽人意.萌生了自己手写海报的想法. 话不多说先贴文档 uni-app官网 其实该文档和微信小程序类似 最终效果,微信 ...
- vue移动端,使用canvas生成商品海报及自定义海报
1.使用 vue-canvas-poster npm i vue-canvas-poster --save 2.在main.js入口文件中引入 import VueCanvasPoster from ...
- uin-app 使用canvas画简易海报
1 canvas画圆角并把图片放进去 uni.downloadFile({url:that.user.url,//图片为网络图片必须要下载到本地获取到图片的临时路径success: function ...
- canvas绘制微信海报分享
前言 最近公司在做一个面向餐饮的微信小程序,公司希望在小程序中嵌入关注公众号的功能,一开始是采用官方提供的official-account,配置公众号关注组件,方便用户快捷关注公众号,但是这个组件的场 ...
- Canvas绘图在微信小程序中的应用:生成个性化海报
Canvas绘图在微信小程序中的应用:生成个性化海报 如极客时间的一些实现案例: 基础语法 Canvas本质是一个可以使用脚本(通常为JavaScript)来绘制图形的 HTML 元素,默认大小为30 ...
- uniapp中使用canvas生成海报
如下图,是在H5中测试,canvas生成后需要保存图片,使用uni.canvasToTempFilePath(官方文档API支持H5的)拿到绘制海报的base64,保存图片,如果提示画布被污染,看看是 ...
最新文章
- 无导师学习_如何找到一位导师并加快学习速度:新手指南。
- crossdomain.xml用法
- 解决spark中遇到的数据倾斜问题
- 【错误记录】前台进程报错 ( Permission Denial: startForeground requires android.permission.FOREGROUND_SERVICE )
- Oracle执行计划中 并行和BUFFER SORT的问题
- AI让边缘更智能 边缘让AI无处不在
- 修改配置使fiddler可以查看https请求
- 使用SQL命令行更改数据库字段类型
- 农行支付php,ECSHOP教程:农行支付接口开发(含手机端)
- python入门指南by许半仙长佩_有哪些好看的耽美文啊?
- 机房(厂房)温度环境监控系统
- python学习笔记9:面向对象编程,类
- OFFICE技术讲座:一级标点压缩共有几种情形
- Java构造方法解析
- 数字图像处理第三版学习笔记一
- 我喜欢的刀刀语录(一)
- docker image 重命名
- Openwrt 18.06 iPhone XR usb tethering导致内核崩溃问题解决方案
- 通过线程八锁问题融会贯通synchronized关键字的使用
- 源自神话的写作要义之英雄