canvas合成图片
//图片合成
function draw(dom){
try{
var data1= new Array();
data1[0] = dom.find('.doodle').attr('src');
data1[1] = dom.find('.frame').attr('src');
var frameImg = dom.find('.frame');
var show=dom.find('.show');
var frameSize = new Image;
frameSize.src = data1[1];
frameSize.width = frameSize.width*0.2;
frameSize.height = frameSize.height*0.2;
var c=document.createElement('canvas'),
ctx=c.getContext('2d'),
len=data1.length;
c.width=frameSize.width;
c.height=frameSize.height;
ctx.rect(0,0,c.width,c.height);
ctx.fillStyle='#FFFFFF';//画布填充颜色
ctx.fill();
function drawing(n){
if(n<len){
var img=new Image;
img.setAttribute('crossOrigin', 'anonymous');
//图片地址域名要和页面的地址域名相同(不同的域名要设置CORS跨域配置)
img.src=data1[n];
img.onload=function(){
if(n==0){
//缩小涂鸦
zoom(frameSize,img,0.85);
}else{
zoom(frameSize,img,1);
}
ctx.drawImage(img,(frameSize.width-img.width)/2,(frameSize.height-img.height)/2,img.width,img.height);
drawing(n+1);递归
}
}else{
//保存生成作品图片
show.attr('src',c.toDataURL("image/png"));
}
}
drawing(0);
}
catch (e){
alert(e.name + ": " + e.message);
}
}
//缩放图片
function zoom(frameImg,img,scale){
var sx = frameImg.width*scale/img.width;
var sy = frameImg.height*scale/img.height;
if(sx > sy){
sx = sy;
img.width = sx*img.width;
img.height = sy*img.height;
}else{
sy = sx;
img.width = sx*img.width;
img.height = sy*img.height;
}
}