canvas合成圖片 聖誕節新技能戴帽
<!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">
</div>
<div id="imgBox" align="center">
<input type="button" value="一鍵合成" onClick="hecheng()">
</div>
<script>
/*
@作者:外號老徐
@郵箱:[email protected]
@網址: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.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)
}
})
canvas合成圖片 聖誕節新技能戴帽