本文最后更新于 2019-02-28【233 天前】,文中所描述的信息可能已发生改变,请谨慎使用。如有问题或建议,欢迎在文章底部留言参与讨论!

自从博客上了星空背景之后,经常有人问我星空背景是怎么实现,我只能说,我不会前端,也没有学过 css,js 等知识,代码是我从网上找的,搜索相关资料调试后加到网站里实现的。

现在把我找到的代码分享给大家,至于如何加入到网站作为背景,还请大家不要做伸手党,我只能说 Handsome 主题需要开启透明背景,其他的需要自己找找资料搜索下,很容易解决。。

canvas 是啥?

<canvas> 是一个可以使用脚本(通常为 JavaScript )来绘制图形的 HTML 元素。例如,它可以用于绘制图表、制作图片构图或者制作简单的(以及不那么简单的)动画。
<canvas> 最早由 Apple 引入 WebKit,用于 Mac OS X 的 Dashboard,随后被各个浏览器实现。如今,所有主流的浏览器都支持它。

上述资料来自:https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API/Tutorial

特效与 Demo

见本站背景,或者单独的一个 Demo 页:https://www.imtqy.com/demo/xingkong/

代码与实现

引入画布

网页的 <body> 中引入 <canvas> 画布 :

<canvas id="canvas"></canvas>

画布内容渲染

利用 JavaScript 进行渲染:

<script>
"use strict";
var canvas = document.getElementById('canvas'),
  ctx = canvas.getContext('2d'),
  w = canvas.width = window.innerWidth,
  h = canvas.height = window.innerHeight,
  hue = 217,
  stars = [],
  count = 0,
  maxStars = 600;
var canvas2 = document.createElement('canvas'),
  ctx2 = canvas2.getContext('2d');
canvas2.width = 100;
canvas2.height = 100;
var half = canvas2.width / 2,
  gradient2 = ctx2.createRadialGradient(half, half, 0, half, half, half);
gradient2.addColorStop(0.025, '#fff');
gradient2.addColorStop(0.1, 'hsl(' + hue + ', 61%, 33%)');
gradient2.addColorStop(0.25, 'hsl(' + hue + ', 64%, 6%)');
gradient2.addColorStop(1, 'transparent');
ctx2.fillStyle = gradient2;
ctx2.beginPath();
ctx2.arc(half, half, half, 0, Math.PI * 2);
ctx2.fill();
function random(min, max) {
  if (arguments.length < 2) {
    max = min;
    min = 0;
  }
  if (min > max) {
    var hold = max;
    max = min;
    min = hold;
  }
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
function maxOrbit(x, y) {
  var max = Math.max(x, y),
    diameter = Math.round(Math.sqrt(max * max + max * max));
  return diameter / 2;
}
var Star = function() {
  this.orbitRadius = random(maxOrbit(w, h));
  this.radius = random(60, this.orbitRadius) / 12;
  this.orbitX = w / 2;
  this.orbitY = h / 2;
  this.timePassed = random(0, maxStars);
  this.speed = random(this.orbitRadius) / 50000;
  this.alpha = random(2, 10) / 10;
  count++;
  stars[count] = this;
}
Star.prototype.draw = function() {
  var x = Math.sin(this.timePassed) * this.orbitRadius + this.orbitX,
    y = Math.cos(this.timePassed) * this.orbitRadius + this.orbitY,
    twinkle = random(10);
  if (twinkle === 1 && this.alpha > 0) {
    this.alpha -= 0.05;
  } else if (twinkle === 2 && this.alpha < 1) {
    this.alpha += 0.05;
  }
  ctx.globalAlpha = this.alpha;
  ctx.drawImage(canvas2, x - this.radius / 2, y - this.radius / 2, this.radius, this.radius);
  this.timePassed += this.speed;
}

for (var i = 0; i < maxStars; i++) {
  new Star();
}
function animation() {
  ctx.globalCompositeOperation = 'source-over';
  ctx.globalAlpha = 0.8;
  ctx.fillStyle = 'hsla(' + hue + ', 64%, 6%, 1)';
  ctx.fillRect(0, 0, w, h)
  ctx.globalCompositeOperation = 'lighter';
  for (var i = 1, l = stars.length; i < l; i++) {
    stars[i].draw();
  };
  window.requestAnimationFrame(animation);
}
animation();
</script>

完整的 html 代码

[collapse title="有点长,不予显示,点击可查看" status="false"]

<html>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
    <meta http-equiv="Cache-Control" content="no-transform"/>
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <meta name="renderer" content="webkit">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>利用 canvas 画布实现网页星空背景 - Quanyin 说</title>
<body>
<canvas id="canvas"></canvas>
<script>
"use strict";
var canvas = document.getElementById('canvas'),
  ctx = canvas.getContext('2d'),
  w = canvas.width = window.innerWidth,
  h = canvas.height = window.innerHeight,
  hue = 217,
  stars = [],
  count = 0,
  maxStars = 600;
var canvas2 = document.createElement('canvas'),
  ctx2 = canvas2.getContext('2d');
canvas2.width = 100;
canvas2.height = 100;
var half = canvas2.width / 2,
  gradient2 = ctx2.createRadialGradient(half, half, 0, half, half, half);
gradient2.addColorStop(0.025, '#fff');
gradient2.addColorStop(0.1, 'hsl(' + hue + ', 61%, 33%)');
gradient2.addColorStop(0.25, 'hsl(' + hue + ', 64%, 6%)');
gradient2.addColorStop(1, 'transparent');

ctx2.fillStyle = gradient2;
ctx2.beginPath();
ctx2.arc(half, half, half, 0, Math.PI * 2);
ctx2.fill();
function random(min, max) {
  if (arguments.length < 2) {
    max = min;
    min = 0;
  }
  if (min > max) {
    var hold = max;
    max = min;
    min = hold;
  }
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function maxOrbit(x, y) {
  var max = Math.max(x, y),
    diameter = Math.round(Math.sqrt(max * max + max * max));
  return diameter / 2;
}
var Star = function() {
  this.orbitRadius = random(maxOrbit(w, h));
  this.radius = random(60, this.orbitRadius) / 12;
  this.orbitX = w / 2;
  this.orbitY = h / 2;
  this.timePassed = random(0, maxStars);
  this.speed = random(this.orbitRadius) / 50000;
  this.alpha = random(2, 10) / 10;
  count++;
  stars[count] = this;
}
Star.prototype.draw = function() {
  var x = Math.sin(this.timePassed) * this.orbitRadius + this.orbitX,
    y = Math.cos(this.timePassed) * this.orbitRadius + this.orbitY,
    twinkle = random(10);
  if (twinkle === 1 && this.alpha > 0) {
    this.alpha -= 0.05;
  } else if (twinkle === 2 && this.alpha < 1) {
    this.alpha += 0.05;
  }
  ctx.globalAlpha = this.alpha;
  ctx.drawImage(canvas2, x - this.radius / 2, y - this.radius / 2, this.radius, this.radius);
  this.timePassed += this.speed;
}
for (var i = 0; i < maxStars; i++) {
  new Star();
}
function animation() {
  ctx.globalCompositeOperation = 'source-over';
  ctx.globalAlpha = 0.8;
  ctx.fillStyle = 'hsla(' + hue + ', 64%, 6%, 1)';
  ctx.fillRect(0, 0, w, h)

  ctx.globalCompositeOperation = 'lighter';
  for (var i = 1, l = stars.length; i < l; i++) {
    stars[i].draw();
  };
  window.requestAnimationFrame(animation);
}
animation();
</script>
</body>
</html>

[/collapse]

代码下载

下载链接:https://www.lanzous.com/i2mt02f

源码来源:https://www.jq22.com/code69
文章目录

推荐使用:阿里云 云翼计划学生优惠、ECS、轻量应用等产品与服务【 点击注册

本文作者:Quanyin Tang

本文链接:利用 canvas 画布实现网页酷炫星空背景 - https://www.imtqy.com/demo-canvas-xingkong.html

版权声明:如无特别声明,本文即为原创文章,仅代表个人观点,版权归 Quanyin 所有,未经允许禁止转载,经授权转载请注明出处!