<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>马赛克</title>
<style>
*{
margin: 0;
padding: 0;
}
body, html {
height: 100%;
overflow: hidden;
}
#test {
position: absolute;
left: 50%;
top: 50%;
transform: translate3d(-50%, -50%, 0);
background-color: gray;
}
</style>
</head>
<body>
<canvas id="test" width="300" height="300">
<span>您的浏览器版本过低,请更换IE-9以上,或使用chrome等其他浏览器</span>
</canvas>
<script type="text/javascript">
/** @type {HTMLCanvasElement} */
//1.获取画布
var canvas = document.querySelector('#test');
if (canvas.getContext) {
//2.获取画笔
var ctx = canvas.getContext('2d');
ctx.globalAlpha = 0.8;
/* 全局透明度的设置
globalAlpha = value
这个属性影响到canvas里所有图形的透明度
有效值的范围 0.0(完全透明) - 1.0(完全不透明)
默认值是1.0
*/
ctx.fillStyle = 'red';
ctx.fillRect(50,50,100,100); //在此处作为destination
ctx.fillStyle = 'pink';
/*ctx.globalCompositeOperation = 'source-atop';*/
ctx.globalCompositeOperation = 'destination-in'
ctx.fillRect(100,100,100,100); //在此处作为source
/* 覆盖合成
source: 新的图像(目标)
destination: 已经绘制过的图形
globalCompositeOperation
source-over(默认值): 源在上面,新的图像层级比较高
source-in : 只留下源与目标的重叠部分(源的那一部分)
source-out : 只留下源超过目标的部分
source-atop: 砍掉源溢出的部分
destination-over: 目标在上面,旧的图像层级比较高
destination-in: 只留下源与目标的重叠部分(目标的那一部分)
destination-out: 只留下目标超过源的部分
destination-atop: 砍掉目标溢出的部分
*/
}
</script>
</body>
</html>