Context对象可以通过改变它的globalAlpha属性来改变生成它的Canvas对象的透明度。globalAlpha属性的取值范围是[0, 1],0表示完全透明,1表示完全不透明。
<!DOCTYPE HTML>
<html>
<body>
<canvas id="canvas" width="600" height="400">
<p>
Your browserdoes not support the canvas element!
</p>
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var context2D = canvas.getContext("2d");
const TIME = 1
var factor = 0;
function changeAlpha() {
factor += TIME / 50;
context2D.globalAlpha = (Math.sin(factor) + 1) / 2; //这里采用简单算法布置透明
}
function draw() {
context2D.clearRect(0, 0, canvas.width, canvas.height);
changeAlpha();
//将上面的圆填充为灰色
context2D.fillStyle = "#FF0000";
context2D.arc(100, 100, 60, 0, Math.PI * 2, false); //注意这里的参数是弧度制,而不是角度制
context2D.fill();
}
setInterval(draw, TIME);
</script>
</body>
</html>
效果图:http://www.31358.cn/html5_study/740.html