canvas繪製氣泡
阿新 • • 發佈:2018-12-01
思路:使用Math.random()函式繪製是個不同位置,大小,顏色的圓形,然後設定定時器,前一個狀態用一個與畫布相同顏色的背景圖片進行覆蓋,改變圓形的位置,每次改變都是在這張空白的背景圖片上面重新進行重新繪製的過程
原始碼:
<!doctype html>
<html>
<head>
<title>test</title>
<meta charset="UTF-8">
</head>
<body>
<canvas id="canvas" Style="border:solid black thin" width="600px" height="500px"></canvas>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
const WIDTH = canvas.width;
const HEIGHT = canvas.height;
var img = new Image();
img.src = "white.png";
var rangeX=[];//用來儲存生成的十組x座標
var rangeY=[];//用來儲存生成的十組y座標
var rangeR=[];//用來儲存生成的十足氣泡的半徑
var red=[];//用來儲存紅色的數值
var green=[];//用來儲存綠色的數值
var blue=[];//用來儲存藍色的數值
for( var i=0;i<20;i++){//事先生成十組氣泡的x座標和半徑
var r = Math.random() * 50;
var x = WIDTH * Math.random();
if (x < r) {
x = r;
}
if (x > WIDTH - r) {
x = WIDTH - r;
}
var y = WIDTH * Math.random();
if (y < r) {
y = r;
}
if (y > WIDTH - r) {
y = WIDTH - r;
}
rangeX[i]=x;
rangeR[i]=r;
rangeY[i]=y;
red[i]=Math.random()*255;
green[i]=Math.random()*255;
blue[i]=Math.random()*255;
}
var algha=0.3;
var tag=1;//設一個標記,標記氣泡是在往下走還是往上走,往下是1,往上是0
var setinterval = setInterval(function () {
context.beginPath();
context.drawImage(img, 0, 0);
for (var i = 0; i < 20; i++) {
var randomX=Math.random()*3;
var randomY=Math.random()*3;
if(tag===1){
if (rangeX[i]+rangeR[i] >= WIDTH && rangeY[i]+rangeR[i] >= HEIGHT) {
tag=0;
}
context.beginPath();
rangeX[i]=rangeX[i]+randomX;
rangeY[i]=rangeY[i]+randomY;
context.arc(rangeX[i], rangeY[i], rangeR[i], 0, Math.PI * 2, false);
context.fillStyle = "rgba("+red[i]+","+green[i]+","+blue[i]+","+algha+")";
context.fill();
} else{
if (rangeX[i]-rangeR[i] <=0 && rangeY[i]-rangeR[i] <=0) {
tag=1;
}
context.beginPath();
rangeX[i]=rangeX[i]-randomX;
rangeY[i]=rangeY[i]-randomY;
context.arc(rangeX[i], rangeY[i], rangeR[i], 0, Math.PI * 2, false);
context.fillStyle = "rgba("+red[i]+","+green[i]+","+blue[i]+","+algha+")";
context.fill();
}
}
context.closePath();
}, 100);
</script>
</body>
</html>
效果圖:
缺陷:
氣泡移動的路徑演算法處理的不是很恰當