1.在繪製每幀圖像時調整
重新繪製每幀中要漸隱的部分,調整顏色和透明度,所有改變都由自己控制,邏輯和代碼可能比較複雜(沒有嘗試過)。
2.使用半透明區域反覆覆蓋
該方法的原理是將目標區域內的原圖像以相同的比例透明化。該方法的核心是使用canvas.getContext(“2d”)的context對象的globalCompositeOperation屬性。將globalCompositeOperation設爲destination-in(在新繪製的區域中顯示原圖像。只有新繪製的區域內的原圖像部分會被顯示,新區域是透明的。),此時將新區域的fillStyle設置一個透明係數,每次填充新區域時,都會將原來的圖透明化。但由於使用了destination-in,沒有被新區域覆蓋的部分會被完全清空,所以只能用於全局透明化或單一圖層。
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.strokeStyle="rgb(255, 0, 0, 1)";//設置線條顏色
ctx.fillStyle="rgba(0, 0, 0, 0.7)";//設置填充區域顏色爲白色,透明度0.7,用於將區域漸變爲透明
var x=0,y=0;
setInterval(draw, 200);
function draw(){
//對區域內圖像進行透明化漸變
ctx.globalCompositeOperation = "destination-in";// 在新繪製的區域中顯示原圖像。只有新繪製的區域內的原圖像部分會被顯示,新區域是透明的。
ctx.fillRect(0,0,150,100);// 填充區域,將目標圖像逐漸透明化
ctx.globalCompositeOperation = "source-over";默認。在原圖像上繪製新圖像。
//繪製直線
ctx.beginPath();
if (x > 150) x=0,y=0;
ctx.moveTo(x,y);
x+=4,y+=4;
ctx.lineTo(x,y);
ctx.stroke();
}
</script>
</body>
</html>