全局不透明度
globalAlpha
globalAlpha = 1 (Default)
var canvas = document.getElementById('canvas')
canvas.width = 1200;
canvas.height = 800;
var context = canvas.getContext("2d");
context.globalAlpha = 0.7; // 设置整个绘制系统的透明度
for(var i = 0; i < 100; i++){
var R = Math.floor(Math.random()*255);
var G = Math.floor(Math.random()*255);
var B = Math.floor(Math.random()*255);
context.fillStyle = `rgb(${R}, ${G}, ${B})`
context.beginPath();
context.arc(Math.random()*canvas.width, Math.random()*canvas.height, Math.random()*100, 0, 2*Math.PI);
context.fill();
}
全局图像重叠
globleCompositeOperation
globleCompositeOperation = "source-over" (Default)
source-over
source-atop
source-in
source-out
destination-over
destination-atop
destination-in
destination-out
lighter
copy
xor
各参数效果演示代码
<!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>Document</title>
<style>
#buttons { 1200px; margin: 10px auto; clear: both;}
#buttons a {font-size: 18px; display: block; float: left; margin-right: 14px;}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<div id="buttons">
<a href="">source-over</a>
<a href="">source-atop</a>
<a href="">source-in</a>
<a href="">source-out</a>
<a href="">destination-over</a>
<a href="">destination-atop</a>
<a href="">destination-in</a>
<a href="">destination-out</a>
<a href="">lighter</a>
<a href="">copy</a>
<a href="">xor</a>
</div>
<script>
draw('source-over');
let buttons = document.getElementById('buttons').getElementsByTagName('a');
for(let i = 0; i < buttons.length; i++) {
buttons[i].onclick = function() {
draw(this.text);
return false;
}
}
function draw(compositeStyle) {
const canvas = document.getElementById('canvas');
canvas.width = 1200;
canvas.height = 800;
const context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
// draw title
context.font = 'bold 40px Arial';
context.textAlign = 'center';
context.textBaseline = 'middle';
context.fillStyle = '#058'
context.fillText(`globalCompositeOperation = ${compositeStyle}`, canvas.width / 2, 60);
// draw a rect
context.fillStyle = 'blue';
context.fillRect(300, 150, 500, 500);
// draw a triangle
context.globalCompositeOperation = compositeStyle;
context.fillStyle = 'red';
context.beginPath();
context.moveTo(700, 250);
context.lineTo(1000, 750);
context.lineTo(400, 750);
context.closePath();
context.fill();
}
</script>
</body>
</html>