HTML5 canvas 透明
透明
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>
<!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>
效果图:
ps:由于是动态图,截屏出来的效果只是一帧,不能出现动态效果,读者可以自己亲手做实验。另外有比较好的方式制作动态图,可以留言,不胜感激。
摘自 冯小卫
补充:web前端 , HTML 5 ,