jquery canvas生成带有二维码的海报

需求:点击图片弹窗生成带有二维码的海报。

遇到相关问题:

1、生成的图片会模糊、不清晰。
2、 苹果手机和安卓手机 文字位置和字体大小有差异。

引入所需要的文件

//jquery.js
<script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
//解决生成的图片模糊、不清晰问题
<script src="/images/202010/hidpi-canvas.min.js"></script>

生成海报图片

<script>
// 执行代码
$(function () {

// 像素密度 如果没这段代码生成的图片可能会模糊
function getPixelRatio(context) {
var backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return (window.devicePixelRatio || 1) / backingStore;
};
//点击事件
$(".myImg").click(function () {
$(".dialog").fadeIn();
var dialogSrc = $(this).attr("src")
var csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
//2.发送请求
$.ajax({
url:"xxxx",
type:"post",
dataType:'json',
headers: {
'X-CSRF-TOKEN': csrfToken
},//设置请求头
success:function (res) {
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");

var ratio = getPixelRatio(context)

canvas.width = 262 * ratio;
canvas.height = 450 * ratio;
context.rect(0, 0, canvas.width * ratio, canvas.height * ratio);
context.fillStyle ="#fff";
context.fill();

var myImage2 =new Image();
//背景图
myImage2.src = dialogSrc
//获取终端
var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;//android终端
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);//ios终端
myImage2.onload =function () {
context.drawImage(myImage2, 0, 0, 262 * ratio, 450 * ratio);
//文本
var text = res.data.company +',' + res.data.sales;
var str =new Array();
str = text.split(",");
var uphight = 0
//解决苹果手机和安卓手机 文字位置和字体大小显示差异问题
for (var i = 0; i < str.length; i++) {
if (isAndroid) {
context.font ="12px Calibri";
context.fillText(str[i], 70, 390 + uphight)
uphight += 20
}

if (isiOS) {
context.font ="20px Calibri";
context.fillText(str[i], 140, 450 * ratio - 120 + uphight)
uphight += 40
}
}
var myImage =new Image();
//二维码图片
myImage.src = res.data.wxcode
myImage.crossOrigin ='Anonymous';
myImage.onload =function () {
context.drawImage(myImage, 30, 380 * ratio, 48 * ratio, 50 * ratio);
var base64 = canvas.toDataURL("image/jpeg", 1.0);
var img = document.getElementById('myPoster');
img.setAttribute('src', base64);
}
}
},
error:function (e) {
console.log('ajax请求异常,异常信息如下:', e);
}
});
});
//关闭弹窗
$(".close").click(function () {
$(".dialog").fadeOut();
})
});
</script>
推荐 收藏
评论(0) 阅读(228)
刷新评论 返回顶部
签名 : 喜欢现在的自己吗?
洋最新博客