效果图
对照图
准备工作
(以下所有片段代码为手敲,难免会有语法错误,请不要复制,文末会发布全部代码)
先准备一张"宇宙星空图",设为背景
<style>
* {
margin:0;
padding:0;
}
body {
background: url(./bg.jpg)
}
</style>
<body>
<canvas id=""constellation>
你的浏览器不支持canvas,请升级你的浏览器
</canvas>
<body>
开始撸代码
观察对照图,可以看出所有的星座都是“点”与“点”的连线,(绘制小的圆形,达到点的效果)
猜想:直接画几个圆然后连线不就可以了?
function draw() {
var canvas = document.getElementById('constellation');
var w = window.innerWidth;
var h = window.innerHeight;
canvas.width = w;
canvas.height = h;
if (!canvas.getContext) return;
var ctx = canvas.getContext("2d");
// 直接绘制圆点
ctx.beginPath()
ctx.arc(100,100,4,0,Math.PI*2,true)
ctx.arc(400,100,4,0,Math.PI*2,true)
ctx.arc(100,400,4,0,Math.PI*2,true)
ctx.fill(); //填充
ctx.beginPath()
ctx.arc(500,100,4,0,Math.PI*2,true)
ctx.arc(800,100,4,0,Math.PI*2,true)
ctx.arc(500,400,4,0,Math.PI*2,true)
ctx.stroke();//连线
}
效果
在一个beginPath()中,使用填充方法(ctx.fill)会默认调用闭合方法(ctx.closePath),
连线方式能实现“点”与“点”的连线,但是“点”是空心的,并没有达到想要的效果(实心点)
猜想
单独绘制每个点,使用填充方法,
然后共同绘制,使用连线方法
function draw() {
var canvas = document.getElementById('constellation');
var w = window.innerWidth;
var h = window.innerHeight;
canvas.width = w;
canvas.height = h;
if (!canvas.getContext) return;
var ctx = canvas.getContext("2d");
// 单独绘制圆点
ctx.beginPath()
ctx.arc(100,100,4,0,Math.PI*2,true)
ctx.fill(); //填充
ctx.beginPath()
ctx.arc(400,100,4,0,Math.PI*2,true)
ctx.fill(); //填充
ctx.beginPath()
ctx.arc(100,400,4,0,Math.PI*2,true)
ctx.fill(); //填充
// 共同绘制
ctx.beginPath()
ctx.arc(500,100,4,0,Math.PI*2,true)
ctx.arc(800,100,4,0,Math.PI*2,true)
ctx.arc(500,400,4,0,Math.PI*2,true)
ctx.stroke();//连线
}
效果
可以看到左边的点已经满足,
将“共同绘制的点”坐标,和“单独绘制的点”坐标重合,
不就能模拟出“点”与“点”的连线了吗(坐标重合图)
改进
将“共同绘制的点”,改为“共同绘制的线”
// 共同绘制
ctx.beginPath()
// 这里参数,X轴,Y轴,半径,开始弧度,结束弧度,顺时针/逆时针,
// 参数太多了吧,而且我只需要线,不需要圆点
// ctx.arc(100,100,4,0,Math.PI*2,true)
// ctx.arc(400,100,4,0,Math.PI*2,true)
// ctx.arc(100,400,4,0,Math.PI*2,true)
// 更改为绘制线
// 这里需要一个起始点,我使用的方法是1号点的坐标,因为是同一个点,所以对页面无影响
// 这么写是为了后面的方法调用更方便
ctx.moveTo(100,100);//起始点
ctx.lineTo(100,100)
ctx.lineTo(400,100)
ctx.lineTo(100,400)
ctx.stroke();
样式
主体“点线连接”已经实现,那么接下来让它变好看,body添加背景图片,绘制的点、线添加颜色
function draw() {
var canvas = document.getElementById('constellation');
var w = window.innerWidth;
var h = window.innerHeight;
canvas.width = w;
canvas.height = h;
if (!canvas.getContext) return;
var ctx = canvas.getContext("2d");
// 设置连线颜色,填充颜色
ctx.font = "40px sans-serif"//文字字体
ctx.strokeStyle = '#bedff8' //连线颜色
ctx.fillStyle = '#96d0fc' //坐标点颜色
ctx.shadowBlur = 10; //设置坐标点阴影的模糊级别
ctx.shadowColor = "#fff" //设置模糊颜色
// 单独绘制圆点
ctx.beginPath()
ctx.arc(100,100,4,0,Math.PI*2,true)
ctx.fill(); //填充
ctx.beginPath()
ctx.arc