通过canvas合成图片
通过canvas合成图片
效果图
页面布局部分
两个图片以及一个canvas画布
<img src="https://qnlite.gtimg.com/qqnewslite/20190924/avatar/head1.png" alt="" id="bg-img">
<img src="http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLFPJR06vhs1iccMd3hFzJ3GXAFm4VljTErIq6ejH3ZicIvfz9DqKxecXkKlUsZtDYYXOo9h0icQWZDw/0" alt="" id="avatar">
<canvas id="my-canvas" width="" height=""></canvas>
JavaScript代码部分
<script src="https://code.jquery.com/jquery-3.4.1.min.js" ></script>
<script type="text/javascript">
// 获取图片及画板对象
var border_img = document.getElementById("border-img");
var avatar = document.getElementById("avatar");
var ca = document.getElementById("my-canvas");
// 创建二维画布,并设置宽高
var ctx = ca.getContext('2d');
ca.width = 200;
ca.height = 200;
// 在画布 (0, 0) 位置作为起点绘制两张图片实现合成
ctx.drawImage(avatar, 0, 0, 200, 200);
ctx.drawImage(border_img, 0, 0, 200, 200);
// 得到图片的Base64编码
dataurl = ca.toDataURL();
</script>
代码合总
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>通过canvas合成图片</title>
</head>
<body>
<img crossorigin="Anonymous" src="https://qnlite.gtimg.com/qqnewslite/20190924/avatar/head1.png" alt="" id="border-img">
<img crossorigin="Anonymous" src="http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLFPJR06vhs1iccMd3hFzJ3GXAFm4VljTErIq6ejH3ZicIvfz9DqKxecXkKlUsZtDYYXOo9h0icQWZDw/0" alt="" id="avatar">
<hr>
<canvas id="my-canvas" width="" height=""></canvas>
<img src="" id="base64-img">
<script src="https://code.jquery.com/jquery-3.4.1.min.js" ></script>
<script type="text/javascript">
var border_img = document.getElementById("border-img");
var avatar = document.getElementById("avatar");
var ca = document.getElementById("my-canvas");
var ctx = ca.getContext('2d');
ca.width = 200;
ca.height = 200;
ctx.drawImage(avatar, 0, 0, 200, 200);
ctx.drawImage(border_img, 0, 0, 200, 200);
dataurl = ca.toDataURL();
$('#base64-img').attr('src', dataurl);
</script>
</body>
</html>