<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Html5 Canvas 实现图片合成</title>
<link rel="stylesheet" href="public.css">
<style>
img{ border:solid 1px #ddd;}
</style>
</head>
<body>
<div align="center">
<img src="images/person.jpg" width="300">
<img src="images/christmas_cap.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=['images/person.jpg','images/christmas_cap.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.setAttribute('crossOrigin', 'anonymous');
img.src=data[n];
img.onload=function(){
if(n == 1){
ctx.rotate(10*Math.PI/180);
ctx.drawImage(img,100,-75, 85,85);
}else{
ctx.drawImage(img,0,0, 300,300);
}
drawing(n+1);//递归
}
}else{
//保存生成作品图片
base64.push(c.toDataURL("image/jpeg",0.8));
fn();
}
}
drawing(0);
}
</script>
<script src="jquery.js"></script>
</body>
</html>
$.extend({
setCookie:function(c_name,value,expiredays){
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+';path=/';
},
getCookie:function(c_name){
if (document.cookie.length>0){
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1){
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
},
clearCookie:function(c_name){
$.setCookie(c_name,'',0)
}
})