console
/*1.自适应canvas
2.
几种运行模式:1随机漂移,2跟随光标,3轨迹刷圈
初始化后,一个飞棍自由漂移
*/
document.body.onload = function () {
new Carxame(document.getElementById('demo'));
}
class Carxame {
constructor(container) {
// 创建canvas元素
this.canvas = document.createElement('canvas');
// 替换原始容器为canvas
container.replaceWith(this.canvas);
// 设置初始样式和尺寸
this.canvas.style.backgroundColor = '#ccc';
this.resize();
this.ctx = this.canvas.getContext('2d');
this.isDrawing = false;
this.points = [];
this.lastPoint = null; // 用于记录上一个点的位置
this.sampleDistance = 5; // 采样距离(像素),可根据需要调整
// 添加窗口resize监听
window.addEventListener('resize', () => this.resize());
this.canvas.addEventListener('mousedown', this.startDrawing.bind(this));
this.canvas.addEventListener('mousemove', this.draw.bind(this));
this.canvas.addEventListener('mouseup', this.stopDrawing.bind(this));
this.canvas.addEventListener('mouseleave', this.stopDrawing.bind(this));
}
startDrawing(event) {
this.isDrawing = true;
this.points.push({ x: event.clientX, y: event.clientY });
this.lastPoint = { x: event.clientX, y: event.clientY };
}
draw(event) {
if (!this.isDrawing) return;
// 计算当前点与上一个点的距离
const distance = Math.sqrt(
Math.pow(event.clientX - this.lastPoint.x, 2) +
Math.pow(event.clientY - this.lastPoint.y, 2)
);
// 如果距离大于采样距离,则记录当前点
if (distance >= this.sampleDistance) {
this.points.push({ x: event.clientX, y: event.clientY });
this.lastPoint = { x: event.clientX, y: event.clientY };
}
// 清除画布并重新绘制
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.beginPath();
this.ctx.moveTo(this.points[0].x, this.points[0].y);
for (let i = 1; i < this.points.length - 2; i++) {
const xc = (this.points[i].x + this.points[i + 1].x) / 2;
const yc = (this.points[i].y + this.points[i + 1].y) / 2;
this.ctx.quadraticCurveTo(this.points[i].x, this.points[i].y, xc, yc);
}
// 封闭样条曲线
if (this.points.length > 2) {
this.ctx.quadraticCurveTo(
this.points[this.points.length - 1].x,
this.points[this.points.length - 1].y,
this.points[0].x,
this.points[0].y
);
}
this.ctx.stroke();
}
stopDrawing() {
this.isDrawing = false;
this.points = [];
this.lastPoint = null;
}
resize() {
// 保持canvas尺寸与窗口一致
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
}
<div id="demo"></div>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}