这是我如何实现它的。关键是在 mousemove 和 mouseup 期间使用 kineticJS 的样条形状并在其中推动点。ev._x, ev._y 是根据这篇文章Tracking mouse position in canvas when no around element exists 计算的 x 和 y 点
请让我知道是否有帮助
tools.pencil = function () {
var tool = this;
this.started = false;
var drawObject;
this.mousedown = function (ev) {
drawObject = new DrawObject();
drawObject.Tool = DrawTool.Pencil;
tool.started = true;
drawObject.currentState = DrawState.Started;
drawObject.StartX = ev._x;
drawObject.StartY = ev._y;
tool.DrawIt(drawObject);
};
this.mousemove = function (ev) {
if (tool.started) {
drawObject.currentState = DrawState.Inprogress;
drawObject.CurrentX = ev._x;
drawObject.CurrentY = ev._y;
tool.DrawIt(drawObject);
};
this.mouseup = function (ev) {
if (tool.started) {
tool.started = false;
drawObject.currentState = DrawState.Completed;
drawObject.CurrentX = ev._x;
drawObject.CurrentY = ev._y;
tool.DrawIt(drawObject);
}
};
this.mouseout = function (ev) {
if (tool.started) {
}
tool.started = false;
};
this.DrawIt = function (drawObject) {
switch (drawObject.currentState) {
case DrawState.Started:
var x= drawObject.StartX,
y = drawObject.StartY;
var pencil = new Kinetic.Spline({
points: [{
x: x,
y: y
}],
stroke: 'red',
strokeWidth: 2,
lineCap: 'round',
tension: 1,
name: shapes.length
});
drawObject.Shape = pencil;
layer.add(pencil);
layer.draw();
break;
case DrawState.Inprogress:
case DrawState.Completed:
var x = drawObject.CurrentX,
y = drawObject.CurrentY;
var pencil = drawObject.Shape;
pencil.attrs.points.push({ x: x, y: y });
pencil.setPoints(pencil.attrs.points);
layer.draw();
if (drawObject.currentState == DrawState.Completed) {
// dosomething
}
break;
}
哪里绘制对象是javascript中的简单空函数
function DrawObject()
{
}
而drawstate是铅笔工具的所有可用状态
var DrawState =
{
Started: 0,
Inprogress: 1,
Completed: 2
}
并且“层”是在 KineticJS 阶段已经添加的简单 KineticJS 层