<body></body>
* {
padding: 0;
margin: 0;
}
canvas {
border: 1px solid #ccc;
}
let isCtrl = false;
let type = "WebGL";
if (!PIXI.utils.isWebGLSupported()) {
type = "canvas";
}
PIXI.utils.sayHello(type);
//Create a Pixi Application
let app = new PIXI.Application({
width: 800, // default: 800
height: 800, // default: 600
antialias: true, // default: false
transparent: false, // default: false
resolution: 1, // default: 1
backgroundColor: 0xffffff,
});
document.body.appendChild(app.view);
const canvas = app.view;
var arr = [];
const r = 12;
let currentPoint;
canvas.addEventListener("click", function (event) {
mousePosFun(canvas, event);
});
function drawLine(from, to) {
drawLine2();
}
function getMiddle(from, to) {
return {
pos: {
x: (from.pos.x + to.pos.x) / 2,
y: (from.pos.y + to.pos.y) / 2,
},
};
}
function drawBaseLine(from, to) {
line = new PIXI.Graphics();
line.lineStyle(4, 0x1a7af8, 1);
line.moveTo(from.x, from.y);
line.lineTo(to.x, to.y);
app.stage.addChild(line);
ss.push(line);
}
let ss = [];
function drawLine2() {
for (let ii = 0; ii < ss.length; ii++) {
const bezier = ss[ii];
app.stage.removeChild(bezier);
}
ss = [];
let start = arr[0];
if (arr.length === 2) {
drawBaseLine(start.pos, arr[1].pos);
}
if (arr.length >= 3) {
for (let i = 1; i < arr.length; i++) {
let control = arr[i];
let end;
if (!arr[i + 1]) {
drawBaseLine(start.pos, arr[i].pos);
return;
} else {
end = getMiddle(arr[i], arr[i + 1]);
}
var bezier = new PIXI.Graphics();
bezier.lineStyle(4, 0x1a7af8, 1);
bezier.moveTo(start.pos.x, start.pos.y);
bezier.quadraticCurveTo(
control.pos.x,
control.pos.y,
end.pos.x,
end.pos.y
);
bezier.endFill();
start = end;
app.stage.addChild(bezier);
ss.push(bezier);
bezier.click = function (e) {};
}
}
}
function drawPoint(x, y, first, last) {
let circle = new PIXI.Graphics();
circle.beginFill(0x9966ff);
circle.drawCircle(0, 0, r);
circle.endFill();
circle.x = x;
circle.y = y;
app.stage.addChild(circle);
return circle;
}
function mousePosFun(canvas, event) {
var rect = canvas.getBoundingClientRect();
// 获取坐标
var x = event.clientX - rect.left * (canvas.width / rect.width);
var y = event.clientY - rect.top * (canvas.height / rect.height);
let circle = drawPoint(x, y, arr.length === 0);
let line;
const data = {
pos: { x, y }, //点的位置
circle, // 圆
line, //线
id: Math.random(),
};
// 看看是否存在前面一项
arr.push(data);
drawLine();
}
This Pen doesn't use any external CSS resources.