该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
主要代码(封装):
(function(){
var Watermark = function(obj,img,options){//可选参数
this.can = obj;
this.text = options.text || '';
this.arrImg = options.arrImg || '';
this.left = options.left || 0;
this.width = options.width || 0;
this.height = options.height || 0;
this.top = options.top || 0;
this.color = options.color || '#000';
this.img = img;
this.family = options.family || '12px Microsoft YaHei';
this.init();
};
Watermark.prototype = {
init:function(){
this.draw();
},
draw:function(){
var canvas = this.can;
var ctx = canvas.getContext("2d");
if(this.text){//如果是文本
var oImg;
if(typeof this.img == 'object'){//如果是img对象
oImg = this.img;
ctx.drawImage(oImg,0,0);//直接显示
}else if(typeof this.img == 'string'){//如果传入的事路径
var newImg = new Image();//创建图片
newImg.src = this.img;
oImg = newImg;
}
ctx.drawImage(oImg,0,0);
ctx.font = this.family;//文字样式
ctx.fillStyle = this.color;//设置文字颜色
ctx.fillText(this.text,this.left,this.top); //追加文字
}else{//如果是水印图片
ctx.drawImage(this.img,0,0);//直接在canvas上drawImage两个图片
ctx.drawImage(this.arrImg,this.left,this.top,this.width,this.height);
}
},
getImg:function() //获取图片路径
{
var image = this.can.toDataURL("image/png");
return image.substring(22);
},
downImg:function() { //下载图片
var image = this.can.toDataURL("image/png").replace("image/png", "image/octet-stream");
window.location.href=image;
}
}
window.Watermark = Watermark;
})()
调用:
//文字水印
var img = new Watermark(canvas,newImgs,{text:'你大爷',left:50,top:50,color:'#fff',family:'italic small-caps bold 20px 楷体',
width:newImgs2.width,
height:newImgs2.height
});
//图片水印
var img2 = new Watermark(canvas1,newImgs,{arrImg:newImgs2,left:50,top:50,
width:newImgs2.width,
height:newImgs2.height
});
参数预览:
//参数设置
/*{
canvas == canvas对象
newImgs == img对象或img图片路径
{
text/arrImg : 文本 显示在图像上的文字/img对象(该参数如果传入text文本 将显示水印,如果传入arrImg对象 将显示传入的img)
left: 文字的left位置
top:文字的top文字
color:'文字的颜色'
family:'文字的样式--大小-字体--粗细' (注:这个根据css的 font属性来设置 font:...)
}
}*/
//方法
//getImg()//获取图片的Base64编码路径
//downImg()//下载图片
//var url = img.getImg();//获取图片路径并把该路径上传到后台 后台通过Base64解码 得到图片
用过AJAX保存到本地
function saveImg(url){
$.ajax({
url:'php/canvas.php',
data:{img:url},
type:'POST',
success: function(msg){
alert(msg)
}
});
}
php:
$saveFile = 'down/';
$imgurl = $_POST['img'];
$img = base64_decode($imgurl);
$t = time().'.jpg';
$save = file_put_contents('../down/'.$t,$img);
if($save)
echo '保存成功';
下载(将文件解压到php坏境->www文件夹下直接运行index.html即可预览dome):
lanrenmaku.com/HTML5/2015_0118_1376.html