您的位置:首页 - 文章 - HTML/CSS, JavaScript - 正文

js利用Canvas制作图片于文字合成图片

基础知识百科: https://www.runoob.com/jsref/dom-obj-canvas.html

我自己亲测得案例,直接上代码:

<!DOCTYPE html>
<html>	<head>	<meta charset="utf-8" />	<title></title>	<script src="static/utils/js/jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script>	<style>	.classname {	width: 100px;	height: 40px;	line-height: 40px;	background-color: #01AAED;	border-radius: 10px;	color: #FFFFFF;	font-size: 12px;	text-align: center;	}	.classimg {	width: 100px;	height: 40px;	line-height: 40px;	background-color: #ff557f;	border-radius: 10px;	color: #FFFFFF;	font-size: 12px;	text-align: center;	margin-top: 10px;	}	.bgimg {	background-color: #007DDB !important;	}	#list {	width: 100%;	height: auto;	}	#list li {	width: 50px;	height: 20px;	background-color: #009688;	margin-top: 5px;	color: white;	font-size: 12px;	text-align: center;	}	</style>	</head>	<body>	<div class="body"> <!-- <canvas id="avatar" style="display: none"></canvas> --> <img src="" id="avatar" />	</div>	<script type="text/javascript">	window.onload = function() {	var a="https://img.sxpcwlkj.com/logo.png";	var b="https://img.sxpcwlkj.com/wp-content/uploads/2017/08/32.jpg";	var c="微信扫码进入小程序";	a="https://img.sxpcwlkj.com/code.png";	b="https://lhym-1301608033.cos.ap-chengdu.myqcloud.com//lhym/2021/7/1/platform_6b071fcc-0e5d-4122-8e21-dab4dafc4f48.jpg";	//解决 图片跨域的问题 drawAndShareImage(a,b,c);	function drawAndShareImage(img,bgimg,text) {	var canvas = document.createElement("canvas");	canvas.width = 700;	canvas.height = 700;	var context = canvas.getContext("2d");	context.rect(0, 0, canvas.width, canvas.height);	context.fillStyle = "#fff";	context.fill();	var myImage = new Image();	myImage.src = bgimg; //背景图片 你自己本地的图片或者在线图片	myImage.crossOrigin = 'Anonymous';	myImage.onload = function() {	context.drawImage(myImage, 0, 0, 700, 700);	context.font = "16px Courier New";	context.fillText(text, 525, 640);	var myImage2 = new Image();	myImage2.src = img; //你自己本地的图片或者在线图片	myImage2.crossOrigin = 'Anonymous';	myImage2.onload = function() {	context.drawImage(myImage2, 520, 450, 150, 150);	var base64 = canvas.toDataURL("image/png"); //"image/png" 这里注意一下	var img = document.getElementById('avatar');	// document.getElementById('avatar').src = base64;	img.setAttribute('src', base64);	}	}	}	}	</script>	</body>
</html>

效果图:

备注: 我用的是七牛云图片,不会有图片跨域的问题,如果你们出现图片跨域的问题要先解决跨域再进行上面的方法合成即可。

本文原创,作者:西决,其版权均为品创网络所有。如需转载,请注明出处:https://www.sxpcwlkj.com/js-canvas/

发表评论