视频演示讲解 https://www.bilibili.com/video/BV1Q8411m7Yh/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="1400" height="700" style="border: 1px solid red"></canvas>
<button id="btn">大范围截图</button>
</body>
</html>
<script>
// 工具类
function getRotateVct(vct, angle) {
let rad = angle * Math.PI / 180;
let x1 = Math.cos(rad) * vct[0] - Math.sin(rad) * vct[1];
let y1 = Math.sin(rad) * vct[0] + Math.cos(rad) * vct[1];
return [x1, y1]; // 返回的是向量
};
function getVctLen([x, y]) {
return Math.sqrt(x * x + y * y);
};
/**
* 根据点在向量上的比例计算点坐标, [xO, yO]为起点,[xVct, yVct]为向量,k 为该点在向量方向上的长度
* 获取
*/
function getPntInVct([xO, yO], [xVct, yVct], k) {
let lenVct = getVctLen([xVct, yVct]); // 获取向量长度
let stdVct;
if (lenVct === 0) {
stdVct = [0, 0];
} else {
stdVct = [xVct / lenVct, yVct / lenVct]; // 单位向量
}
return [xO + k * stdVct[0], yO + k * stdVct[1]];
};
vct = function (start, end) {
let x = end[0] - start[0];
let y = end[1] - start[1];
return [x, y];
};
/**
* P 绕 O 点逆时针旋转angle角度后得到新的点坐标
*/
getRotatePnt = function (O, P, angle) {
if (angle === 0) {
return P;
}
let vctOP = vct(O, P),
OP = getVctLen(vctOP);
let dvctOQ = getRotateVct(vctOP, angle);
let newPoint = getPntInVct(O, dvctOQ, OP);
return newPoint;
};
/**
* 在一段三次贝塞尔曲线上均匀取点, 不包括终点
* @param counts 一段贝塞尔曲线中取点的数量
*/
getPntsOf3Bezier = function (p0, p1, p2, p3, counts) {
let per = counts && counts != 0 ? 1 / counts : 0.02; //取点间隔
let points = [];
for (let t = 0; t <= 0.999999; t += per) {
points.push(getPntIn3Bezier(p0, p1, p2, p3, t));
}
return points;
};
/**
* 获取三次贝塞尔曲线上的一点,t∈[0,1]
* @param t 介于0 ~ 1, 表示点在曲线中的相对位置
*/
getPntIn3Bezier = function (p0, p1, p2, p3, t) {
let t_ = 1 - t;
let x = p0[0] * t_ * t_ * t_ + 3 * p1[0] * t * t_ * t_ + 3 * p2[0] * t * t * t_ + p3[0] * t * t * t,
y = p0[1] * t_ * t_ * t_ + 3 * p1[1] * t * t_ * t_ + 3 * p2[1] * t * t * t_ + p3[1] * t * t * t;
return [x, y];
};
function getMousePos(myCanvas, e) {
let downX;
let downY;
if (e.x && e.y) {
downX = e.x;
downY = e.y;
} else {
downX = e.clientX;
downY = e.clientY;
}
let { left, top } = myCanvas.getBoundingClientRect();
let xDist = downX - left;
let yDist = downY - top;
return {
x: xDist,
y: yDist,
};
}
// -------------------------------------
// 常量
const SOLIDCOLOR = '#CCCCCC70'; // 实线颜色
const DASHEDCOLOR = '#CCCCCC25'; // 虚线颜色
const ZEROCOLOR = '#358bf3'; // 0 点坐标系颜色
const GRIDSIZE = 2; // 一个正方形网格的宽高大小, 一个GRIDSIZE视为一个单位
// -------------------------------------
// 三角形点状元素
class MyTriangle {
constructor(x, y, width, height, angle = 0) { // 相对坐标
this.pointList = []
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.angle = angle;
this.isPointIn = false;
this.fillStyle = "#69b1ff";
}
getPointsWithPosAndAngle(x, y, width, height) {
let O = [x, y];
let point1 = [x, y - height / 2];
let point2 = [x - width / 2, y + height / 2];
let point3 = [x + width / 2, y + height / 2];
let vctp1 = [point1[0] - O[0], point1[1] - O[1]];
let vctp2 = [point2[0] - O[0], point2[1] - O[1]];
let vctp3 = [point3[0] - O[0], point3[1] - O[1]];
let rvctp1 = getRotateVct(vctp1, this.angle);
let rvctp2 = getRotateVct(vctp2, this.angle);
let rvctp3 = getRotateVct(vctp3, this.angle);
return [
[rvctp1[0] + x, rvctp1[1] + y],
[rvctp2[0] + x, rvctp2[1] + y],
[rvctp3[0] + x, rvctp3[1] + y],
];
}
draw(ctx, x, y, width, height) { // 真正绘制用像素坐标
ctx.save();
ctx.beginPath();
this.getPointsWithPosAndAngle(x, y, width, height).forEach((p, i) => {
if (i == 0) {
ctx.moveTo(p[0], p[1]);
} else {
ctx.lineTo(p[0], p[1]);
}
})
ctx.closePath();
ctx.fillStyle = this.fillStyle;
ctx.fill();
this.setPointIn(ctx);
ctx.restore();
}
setPointIn(ctx) {
this.isPointIn = ctx.isPointInPath(GridSystem.currentMousePos.x, GridSystem.currentMousePos.y);
if (!this.isPointIn) {
this.fillStyle = "#69b1ff";
} else {
this.fillStyle = "#003eb3";
}
}
}
class Link {
startNode = [];
endNode = [];
constructor(startNode, endNode) {
this.startNode = startNode;
this.endNode = endNode;
}
draw(ctx, startPos, endPos) {
let vct = [endPos.x - startPos.x, endPos.y - startPos.y];
let cp1 = getPntInVct([startPos.x, startPos.y], vct, getVctLen(vct) * 0.4);
let cp2 = getPntInVct([startPos.x, startPos.y], vct, getVctLen(vct) * 0.6);
let rcp1 = getRotatePnt([startPos.x, startPos.y], cp1, 25);
let rcp2 = getRotatePnt([endPos.x, endPos.y], cp2, 25);
let points = getPntsOf3Bezier([startPos.x, startPos.y], rcp1, rcp2, [endPos.x, endPos.y], 50);
ctx.save();
ctx.beginPath();
points.forEach((p, i) => {
if (i == 0) {
ctx.moveTo(p[0], p[1]);
} else {
ctx.lineTo(p[0], p[1]);
}
})
ctx.lineWidth = 3;
ctx.strokeStyle = "#fc0"
ctx.stroke();
ctx.closePath();
ctx.restore();
}
}
// 绘制类,主类
class GridSystem {
static currentMousePos = {
x: 0,
y: 0
}
constructor(canvasDom) {
// 当前 canvas 的 0 0 坐标,我们设置 canvas 左上角顶点为 0 0,向右👉和向下👇是 X Y 轴正方向,0,0 为 pageSlicePos 初始值
this.pageSlicePos = {
x: 0,
y: 0,
};
this.scale = 1; // 缩放比例
this.myCanvas = canvasDom;
this.ctx = this.myCanvas.getContext('2d');
this.canvasWidth = this.ctx.canvas.width;
this.canvasHeight = this.ctx.canvas.height;
this.hoverNode = null;
let triangle = new MyTriangle(-600, 600, 50, 50);
let triangle2 = new MyTriangle(1800, 1800, 50, 50);
let line = new Link(triangle, triangle2);
this.features = [
triangle,
triangle2,
];
this.lines = [
line,
]
this.firstPageSlicePos = Object.freeze({
x: this.pageSlicePos.x,
y: this.pageSlicePos.y
}); // 记录一开始的的中心点坐标,不会改变的
this.extent = [750, 800, 750, 800] // 限制画布拖拽范围: 上右下左,顺时针
this.initEventListener();
}
initEventListener() {
this.myCanvas.addEventListener("mousemove", this.mouseMove.bind(this));
this.myCanvas.addEventListener("mousedown", this.mouseDown.bind(this));
this.myCanvas.addEventListener("mousewheel", this.mouseWheel.bind(this));
}
/**
* 绘制网格
*/
drawLineGrid = () => {
// this.ctx.rotate(30)
this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
/*获取绘图工具*/
// 设置网格大小
var girdSize = this.getPixelSize(GRIDSIZE);
// 获取Canvas的width、height
var CanvasWidth = this.ctx.canvas.width;
var CanvasHeight = this.ctx.canvas.height;
// 在 pageSlicePos 的 x,y 点位画一个 10 * 10 的红色标记用来表示当前页面的 0 0 坐标
this.ctx.fillRect(this.pageSlicePos.x, this.pageSlicePos.y, 10, 10); // 效果图红色小方块
this.ctx.fillStyle = 'red';
const canvasXHeight = CanvasHeight - this.pageSlicePos.y;
const canvasYWidth = CanvasWidth - this.pageSlicePos.x;
// 从 pageSlicePos.y 处开始往 Y 轴正方向画 X 轴网格
const xPageSliceTotal = Math.ceil(canvasXHeight / girdSize);
for (let i = 0; i < xPageSliceTotal; i++) {
this.ctx.beginPath(); // 开启路径,设置不同的样式
this.ctx.moveTo(0, this.pageSlicePos.y + girdSize * i);
this.ctx.lineTo(CanvasWidth, this.pageSlicePos.y + girdSize * i);
this.ctx.strokeStyle = i === 0 ? ZEROCOLOR : (i % 5 === 0 ? SOLIDCOLOR : DASHEDCOLOR); // 如果为 0 则用蓝色标记,取余 5 为实线,其余为比较淡的线
this.ctx.stroke();
}
// 从 pageSlicePos.y 处开始往 Y 轴负方向画 X 轴网格
const xRemaining = this.pageSlicePos.y;
const xRemainingTotal = Math.ceil(xRemaining / girdSize);
for (let i = 0; i < xRemainingTotal; i++) {
if (i === 0) continue;
this.ctx.beginPath(); // 开启路径,设置不同的样式
this.ctx.moveTo(0, this.pageSlicePos.y - girdSize * i); // -0.5是为了解决像素模糊问题
this.ctx.lineTo(CanvasWidth, this.pageSlicePos.y - girdSize * i);
this.ctx.strokeStyle = i === 0 ? ZEROCOLOR : (i % 5 === 0 ? SOLIDCOLOR : DASHEDCOLOR);// 如果为 0 则用蓝色标记,取余 5 为实线,其余为比较淡的线
this.ctx.stroke();
}
// 从 pageSlicePos.x 处开始往 X 轴正方向画 Y 轴网格
const yPageSliceTotal = Math.ceil(canvasYWidth / girdSize); // 计算需要绘画y轴的条数
for (let j = 0; j < yPageSliceTotal; j++) {
this.ctx.beginPath(); // 开启路径,设置不同的样式
this.ctx.moveTo(this.pageSlicePos.x + girdSize * j, 0);
this.ctx.lineTo(this.pageSlicePos.x + girdSize * j, CanvasHeight);
this.ctx.strokeStyle = j === 0 ? ZEROCOLOR : (j % 5 === 0 ? SOLIDCOLOR : DASHEDCOLOR);// 如果为 0 则用蓝色标记,取余 5 为实线,其余为比较淡的线
this.ctx.stroke();
}
// 从 pageSlicePos.x 处开始往 X 轴负方向画 Y 轴网格
const yRemaining = this.pageSlicePos.x;
const yRemainingTotal = Math.ceil(yRemaining / girdSize);
for (let j = 0; j < yRemainingTotal; j++) {
if (j === 0) continue;
this.ctx.beginPath(); // 开启路径,设置不同的样式
this.ctx.moveTo(this.pageSlicePos.x - girdSize * j, 0);
this.ctx.lineTo(this.pageSlicePos.x - girdSize * j, CanvasHeight);
this.ctx.strokeStyle = j === 0 ? ZEROCOLOR : (j % 5 === 0 ? SOLIDCOLOR : DASHEDCOLOR);// 如果为 0 则用蓝色标记,取余 5 为实线,其余为比较淡的线
this.ctx.stroke();
}
if (this.constructor.name == "GridSystem") { // 如果是主类
document.dispatchEvent(new CustomEvent("draw", { detail: this }));
}
this.drawFeatures();
};
/**
* 滚轮缩放倍数
*/
mouseWheel(e) {
console.log(e.wheelDelta, " e");
if (e.wheelDelta > 0) {
if (this.scale < 5) {
this.scale++;
}
} else {
if (this.scale > .2) {
this.scale -= .1;
}
}
console.log(this.scale, "scale");
}
mouseMove(e) {
GridSystem.currentMousePos.x = e.clientX;
GridSystem.currentMousePos.y = e.clientY;
}
/**
* 拖动 canvas 动态渲染,拖动时,动态设置 pageSlicePos 的值
* @param e Event
*/
mouseDown(e) {
const downX = e.clientX;
const downY = e.clientY;
const { x, y } = this.pageSlicePos;
this.hoverNode = this.features.find(f => f.isPointIn && f);
if (this.hoverNode) {
let { x: fx, y: fy } = this.hoverNode;
document.onmousemove = (ev) => {
const moveX = ev.clientX;
const moveY = ev.clientY;
let { x: x1, y: y1 } = this.getRelativePos({ x: downX, y: downY })
let { x: x2, y: y2 } = this.getRelativePos({ x: moveX, y: moveY })
this.hoverNode.x = fx + (x2 - x1);
this.hoverNode.y = fy + (y2 - y1);
document.onmouseup = (en) => {
document.onmousemove = null;
document.onmouseup = null;
};
}
} else {
document.onmousemove = (ev) => {
const moveX = ev.clientX;
const moveY = ev.clientY;
this.pageSlicePos.x = x + (moveX - downX);
this.pageSlicePos.y = y + (moveY - downY);
document.onmouseup = (en) => {
document.onmousemove = null;
document.onmouseup = null;
};
}
}
}
getPixelPos(point, block) {
return {
x: this.pageSlicePos.x + (point.x / GRIDSIZE) * this.scale,
y: this.pageSlicePos.y + (point.y / GRIDSIZE) * this.scale,
};
}
getRelativePos(point, block) {
return {
x: ((point.x - this.pageSlicePos.x) / this.scale) * GRIDSIZE,
y: ((point.y - this.pageSlicePos.y) / this.scale) * GRIDSIZE,
};
}
getPixelSize(size) {
return size * this.scale;
}
getRelativeSize(size) {
return size / this.scale;
}
getPixelPosAndWH(block) { // 元素的像素坐标和大小
let { x, y } = this.getPixelPos(block, block);
var width = this.getPixelSize(block.width, block);
var height = this.getPixelSize(block.height, block);
return { x, y, width, height, }
}
getRelativePosAndWH(x1, y1, width1, height1, block) { // 元素的绝对坐标和大小
let { x, y } = this.getRelativePos(
{ x: x1, y: y1 }, block
);
let width = this.getRelativeSize(width1, block)
let height = this.getRelativeSize(height1, block)
return { x, y, width, height }
}
drawFeatures() {
this.features.forEach(f => {
let { x, y, width, height } = this.getPixelPosAndWH(f);
f.draw(this.ctx, x, y, width, height);
})
this.lines.forEach(f => {
f.draw(this.ctx, this.getPixelPosAndWH(f.startNode), this.getPixelPosAndWH(f.endNode));
})
}
}
let gls = new GridSystem(document.querySelector('#myCanvas'));
btn.onclick = () => {
let canvas2 = document.createElement('canvas');
canvas2.width = 3000;
canvas2.height = 1800;
let gls2 = new GridSystem(canvas2);
gls2.features = gls.features;
gls2.lines = gls.lines;
gls2.scale = .5;
gls2.pageSlicePos.x = gls2.ctx.canvas.width / 2;
gls2.pageSlicePos.y = gls2.ctx.canvas.height / 2;
gls2.drawLineGrid();
let base64Str = canvas2.toDataURL("png", 1);
let aLink = document.createElement("a");
aLink.style.display = "none";
aLink.href = base64Str;
aLink.download = "截图.png";
// 触发点击-然后移除
document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink);
canvas2 = null;
gls2 = null;
}
(function main() {
gls.drawLineGrid();
gls.features[0].x += 1.5
requestAnimationFrame(main);
})()
</script>
<style>
body {
margin: 0;
}
</style>