H5canvas 4:图像混合

这里要讲的是

globalCompositeOperation

其属性设置或返回如何将一个源(新的)图像绘制到目标(已有)的图像上。
源图像 = 您打算放置到画布上的绘图。
目标图像 = 您已经放置在画布上的绘图

W3school上对于属性值介绍是这样的:
H5canvas 4:图像混合
我个人的网页中选择了几个试了一下,跟PS里面图片混合模式差不多。

Js代码:

var can=null;
var ctx=null;
window.function(){
	can=document.getElementById("mycan");
	ctx=can.getContext("2d");
	var sourceInBtn=document.getElementById("sourceInBtn");
	var lighterBtn=document.getElementById("lighterBtn");
	var sourceAtopBtn=document.getElementById("source-atopBtn");
	var restoreBtn=document.getElementById("restoreBtn");
	ctx.save();//保存
	
	//source-over
	sourceOverBtn.onclick=function(){
		var img=new Image();
		img.src="img/4.jpg";
		var img0=new Image();
		img0.src="img/9.png";
		img.function(){
			ctx.drawImage(img,0,0,500,300);
			ctx.globalCompositeOperation="source-over";
			img0.function(){
				ctx.drawImage(img0,20,0,180,120);
			}
		}
	}
	
	//lighter
	lighterBtn.onclick=function(){
		var img=new Image();
		img.src="img/4.jpg";
		var img0=new Image();
		img0.src="img/8.png";
		img.function(){
			ctx.drawImage(img,0,0,500,300);
			ctx.globalCompositeOperation="lighter";
			img0.function(){
				ctx.drawImage(img0,0,0,500,300);
			}
		}
	}
	//source-atop
	sourceAtopBtn.onclick=function(){
		var img=new Image();
		img.src="img/4.jpg";
		var img0=new Image();
		img0.src="img/3.png";
		img.function(){
			ctx.drawImage(img,0,0,500,300);
			ctx.globalCompositeOperation="source-atop";
			img0.function(){
				ctx.drawImage(img0,0,0,500,300);
			}
		}
	}
	restoreBtn.onclick=function(){
		ctx.clearRect(0,0,can.width,can.height);
		ctx.restore();//恢复
		ctx.save();
	}
}

html代码和css,这些可以自己调。

<h2>图像混合</h2>		
		<div id="img">
			<div class="pic" style="background-image: url(img/4.jpg);"></div>
			<div class="pic" style="background-image: url(img/8.png);"></div>
			<div class="pic" style="background-image: url(img/3.png);"></div>
			<div class="pic" style="background-image: url(img/9.png);"></div>
		</div>
		<div class="clear"></div>
		<canvas id="mycan" width="500" height="300"></canvas>
		<div id="btn-group">
			<input type="button" value="source-over" id="sourceOverBtn" />			
			<input type="button" value="source-atop" id="source-atopBtn" />
			<input type="button" value="lighter" id="lighterBtn" />
			<input type="button" value="重置" id="restoreBtn" />
		</div>
@charset "utf-8";
body{
	margin: 0;
	padding: 0;
	text-align: center;
}
#mycan{
	border: 1px solid;
	background-position: 50% 50%;
	background-size: 100%;
	background-repeat: no-repeat;
}
.pic{
	border: 1px solid beige;
	float: left;
	width: 200px;
	height: 150px;
	background-size: 100% 100%;
	background-position: center;
	position: relative;
	left: 17%;
	margin: 20px;
	text-align: center;
}
.clear{
	clear: both;
}

相关文章: