<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="keywords" content="前端老徐、外号老徐、老徐博客、老徐主页、前端工程师、web前端、loveqiao、html5、css3、jquery">
<meta name="description" content="一个前端工作者的学习笔记">
<title>Html5 Canvas 实现图片合成</title>
<link rel="stylesheet" href="http://www.loveqiao.com/css/public.css">
<style>
img{ border:solid 1px #ddd;width:300px;height:300px;}
</style>
</head>
<body>
<div align="center">
<img src="img1.png" width="300">
<img src="img2.png" width="300">
<img src="api.jpg" width="300">
<img src="img4.png" width="300">
</div>
<div id="imgBox" align="center">
<input type="button" value="一键合成" onClick="hecheng()">
</div>
<script>
/*
@作者:外号老徐
@邮箱:442413729@qq.com
@网址:http://www.loveqiao.com
*/
function hecheng(){
draw(function(){
document.getElementById('imgBox').innerHTML='<p style="padding:10px 0">合成图片成功!可以鼠标另存图片查看我是否是一张图片~~!</p><img src="'+base64[0]+'">';
})
}
var data=['img1.png','img2.png','api.jpg','img4.png'],base64=[];
function draw(fn){
var c=document.createElement('canvas'),
ctx=c.getContext('2d'),
len=data.length;
c.width=290;
c.height=290;
ctx.rect(0,0,c.width,c.height);
ctx.fillStyle='#fff';
ctx.fill();
function drawing(n){
if(n<len){
var img=new Image;
img.crossOrigin = 'Anonymous'; //解决跨域
img.src=data[n];
img.οnlοad=function(){
ctx.drawImage(img,0,0,290,290);
drawing(n+1);//递归
}
}else{
//保存生成作品图片
base64.push(c.toDataURL("image/jpeg",0.8));
//alert(JSON.stringify(base64));
fn();
}
}
drawing(0);
}
</script>
<script src="http://cdn.loveqiao.com/jquery.js"></script>
<script src="http://www.loveqiao.com/js/public.js"></script>
</body>
</html>