文章目录
- 网格线
- 心形
- 对角线
- 科技风圆弧
网格线
const canvas = document.getElementsByTagName('canvas')[0];//这么写是为了获取canvas ctx 属性方法推荐
const ctx = canvas.getContext('2d');
const { offsetWidth, offsetHeight } = document.body;
canvas.width = offsetWidth;
canvas.height = offsetHeight;
for (let index = 0; index < offsetWidth; index += 100) {
ctx.beginPath();
ctx.moveTo(index, 0);
ctx.lineTo(index, offsetHeight);
ctx.strokeStyle = "#ddd";
ctx.stroke();
ctx.closePath();
}
for (let index = 0; index < offsetHeight; index += 100) {
ctx.beginPath();
ctx.moveTo(0, index);
ctx.lineTo(offsetWidth, index);
ctx.strokeStyle = "#ddd";
ctx.stroke();
ctx.closePath();
}
心形
const canvas = document.getElementsByTagName('canvas')[0];//这么写是为了获取canvas ctx 属性方法推荐
const ctx = canvas.getContext('2d');
const accuracy = 50;//渲染精度
function drawHeart(x, y, r) {
ctx.save();//保存 rotate translate 状态
ctx.beginPath();
ctx.translate(x, y);
ctx.rotate(Math.PI);
for (let i = 0; i < accuracy; i++) {
const step = i / accuracy * (Math.PI * 2);//设置心上面两点之间的角度,具体分成多少份,好像需要去试。
const xx = r * (16 * Math.pow(Math.sin(step), 3));
const yy = r * (13 * Math.cos(step) - 5 * Math.cos(2 * step) - 2 * Math.cos(3 * step) - Math.cos(4 * step));
ctx.lineTo(xx, yy);
ctx.fillStyle = randomColor();
ctx.fill();
}
ctx.closePath();
ctx.restore();// 释放状态
}
drawHeart(200, 300, 5);
drawHeart(300, 200, 5);
function randomColor() {
return "#" + Math.round(Math.random() * 0xffffff).toString(16);
}
对角线
const { offsetWidth, offsetHeight } = document.body;
for (let index = 0; index < offsetWidth; index += 50) {
ctx.beginPath();
ctx.moveTo(index, offsetHeight);
ctx.lineTo(offsetWidth - index, 0);
ctx.strokeStyle = "#ddd";
ctx.stroke();
ctx.closePath();
}
科技风圆弧
const { offsetWidth, offsetHeight } = document.body;
canvas.width = offsetWidth;
canvas.height = offsetHeight;
technologyLine(offsetHeight, 40);
function technologyLine(h, space) {
for (let i = 0; i < h; i += space) {
ctx.beginPath();
ctx.strokeStyle = "#ccc";
ctx.moveTo(0, i);
ctx.lineTo(i, h);
ctx.moveTo(offsetWidth, i);
ctx.lineTo(offsetWidth - i, h);
ctx.stroke();
ctx.closePath();
}
}
for (let index = 0; index < offsetWidth; index += 40) {
ctx.beginPath();
ctx.moveTo(index, 0);
ctx.lineTo(offsetWidth, index);
ctx.strokeStyle = "#ccc";
ctx.stroke();
ctx.closePath();
}
for (let index = 0; index < offsetWidth; index += 40) {
ctx.beginPath();
ctx.moveTo(index, 0);
ctx.lineTo(offsetWidth, index);
ctx.strokeStyle = "#ccc";
ctx.moveTo(index, 0);
ctx.lineTo(0, offsetWidth - index);
ctx.stroke();
ctx.closePath();
}