html
<canvas id="canvas" width="375px" height="667px" style="display:none"></canvas>
<div class="box" style="width: 100%;height: 667px;"></div>
<input id="download" type="button" value="下载" style="margin-left: 150px;" />
js
let cvas = document.getElementById('canvas')
let content = cvas.getContext('2d')
let src = './image/code.png'
let str = '我是xxx,2020xxx全球主题设计大赛,'
let config = {
src: './image/code.png',
fillStyle: '#7a7a7a',
font: '14px Adobe Ming Std',
str: '我是xxx,2020xxx全球主题设计大赛,',
}
create.init(cvas, content, config)
// 点击生成
$('#download').click(function () {
let img = $('.box').children('img').attr("src");
let alink = document.createElement("a");
alink.href = img;
alink.download = "二维码.png";
alink.click();
})
**canvas.js**
function CanvasText(ctx, cvas, str, font, fontColor = '') {
ctx.font = font
ctx.fillStyle = fontColor
let lineWidth = 0
let canvasWidth = cvas.width - 100
let initHeight = 350 //字体初始高度
let initX = 50 //字体初始x坐标
let strSubIndex = 0
for (let i = 0, len = str.length; i < len; i++) {
lineWidth += ctx.measureText(str[i]).width //获取文字全部长度
if (lineWidth > canvasWidth) {
ctx.fillText(str.substring(strSubIndex, i), initX, initHeight)
initHeight += 25;
lineWidth = 25;
strSubIndex = i;
}
if (i === len - 1) {
ctx.fillText(str.substring(strSubIndex, i + 1), initX, initHeight)
}
}
}
var create = {
/** * * @param {*画布} cvas * @param {*获取画布} content * @param {*图片路径} src * @param {*图片y轴坐标} y * @param {*图片宽} imgWidth * @param {*图片高} imgHeight * @param {*字体样式} fillStyle * @param {*字体大小} font * @param {*文字} str * @param {*绘制图片添加的节点属性} box */
init(cvas, content, config) {
let imgbg = new Image
let scrW = document.documentElement.clientWidth
let scrH = document.documentElement.clientHeight
imgbg.src = config.src
imgbg.setAttribute("crossorigin", 'anonymous')
imgbg.onload = function () {
let imgX = (scrW - 150) / 2 //图片居中显示 X
content.drawImage(imgbg, imgX, config.y || 480, config.imgWidth || 150, config.imgHeight || 150)
CanvasText(content, cvas, config.str, config.font, config.fillStyle) // 绘制文字
let img = new Image()
img.src = cvas.toDataURL('image/png');
let el = document.getElementsByClassName(config.box || 'box')[0]
el.appendChild(img);
}
}
}
PS:还得注意一下建议搭建本地服务运行,不然报错,第二次刷新页面会找到图片base64的路径
原文链接:https://blog.csdn.net/weixin_42164539/article/details/105839463
本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。
还没有人抢沙发呢~