簡體   English   中英

使畫布透明

[英]Make canvas transparent

我的身體是這樣的:

body
{
    background-image:url('../images/bg.png');
    background-repeat:no-repeat;
    background-size:fixed 100vw;
    background-position:center;
}

問題是,畫布是白色的而不是透明的。 有沒有一種方法可以使它透明,以便我可以將dna波放置在背景之上?

Codepen示例

默認情況下,畫布是透明的。

嘗試設置頁面背景圖像,然后在其上放置畫布。 如果在畫布上未繪制任何內容,則可以完全看到頁面背景。

你應該試試

context.clearRect(0,0,width,height);

有關更多信息,請參見如何在html5中制作透明畫布?

一種簡單的方法是使用屏幕外的畫布。

首先將其上下文的globalAlpha值設置為0到1之間的值,這將確定您先前的圖形消失的速度。

然后,在動畫循環中,在制作新圖紙之前,

  • 清除屏幕外上下文
  • 在屏幕外的一個上繪制可見的畫布,
  • 清除可見的畫布
  • 將屏幕外的一個拖回可見的一個

在此過程中,圖像將失去透明度。

 var clear = function(){ // clear the clone canvas cloneCtx.clearRect(0,0,canvasWidth, canvasHeight) // this should be needed at init and when canvas is resized but for demo I leave it here cloneCtx.globalAlpha = '.8'; // draw ou visible canvas, a bit less opaque cloneCtx.drawImage(context.canvas, 0,0) // clear the visible canvas context.clearRect(0,0,canvasWidth, canvasHeight) // draw back our saved less-opaque image context.drawImage(clone, 0,0) } var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'), // create an offscreen clone clone = canvas.cloneNode(), cloneCtx = clone.getContext('2d'), canvasWidth = canvas.width = clone.width =window.innerWidth, canvasHeight = canvas.height = clone.height = window.innerHeight, globalTick = 0, points = [], pointCount = 12, pointSpeed = 6, spacing = canvasWidth / pointCount, pointCount = pointCount + 2, verticalPointRange = 60, randomRange = function(min, max){ return Math.floor( (Math.random() * (max - min + 1) ) + min); }, iPath, iPoints; var Point = function(x, y, alt){ this.x = x; this.y = y; this.yStart = y; this.alt = alt; } Point.prototype.update = function(i){ var range = (this.alt) ? verticalPointRange : -verticalPointRange; this.x += pointSpeed; this.y = (this.yStart) + Math.sin(globalTick/14) * -range; if(this.x > (canvasWidth + spacing)){ this.x = -spacing; var moved = points.splice(i, 1); points.unshift(moved[0]); } } var updatePoints = function(){ var i = points.length; while(i--){ points[i].update(i); } } for(iPoints = 0; iPoints < pointCount; iPoints++){ var alt = (iPoints % 2 === 0); var offset = (alt) ? verticalPointRange : -verticalPointRange; points.push(new Point(spacing * (iPoints-1), canvasHeight/2, alt)); } var renderPath = function(){ context.beginPath(); context.moveTo(points[0].x, points[0].y); for(iPath = 1; iPath < pointCount; iPath++){ context.lineTo(points[iPath].x, points[iPath].y); } context.stroke(); } var loop = function(){ requestAnimationFrame(loop, canvas); clear(); updatePoints(); renderPath(); globalTick++; }; loop(); 
 canvas { display: block; } body{ background-color: ivory; } 
 <canvas id="canvas"></canvas> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM