问题
I'm using fabric.js in one project, where user can draw on canvas, and save to png image (using canvas.toDataURL() function). However, we noticed if user moved an object and clicked on Save button, it saves a border and corners of previously moved object (borders are always displayed when you move or resize object). So we need a way to remove object borders before saving, is that possible?
回答1:
Yes. You probably want to deactivate all objects before saving an image:
canvas.deactivateAll().renderAll();
(renderAll
updates actual visual state after deactivation of all objects)
回答2:
If you like the idea of your users moving and scaling the Paths drawn on the canvas. I would go with kangax's suggestion.
Alternatively if you want to change the behaviour stlightly, you can set the hasBorders
and hasControls
fields on each path element to false. Then you will never see the controls/borders, and therefore they can never be printed. But it also means that you cannot rotate or scale the Paths, but you can still move them.
Or you could go a step further and make the paths unselectable (making them unmovable, which you may or may not want). So you could set selectable
field on each path to false.
To make all of this easier on you you could override _finalizeDrawingPath
from fabric.js, by adding the following code in your own js file after you have included fabric.js
fabric.Canvas.prototype._finalizeDrawingPath = function() {
this.contextTop.closePath();
this._isCurrentlyDrawing = false;
var minX = utilMin(this._freeDrawingXPoints),
minY = utilMin(this._freeDrawingYPoints),
maxX = utilMax(this._freeDrawingXPoints),
maxY = utilMax(this._freeDrawingYPoints),
ctx = this.contextTop,
path = [ ], xPoint, yPoint,
xPoints = this._freeDrawingXPoints,
yPoints = this._freeDrawingYPoints;
path.push('M ', xPoints[0] - minX, ' ', yPoints[0] - minY, ' ');
for (var i = 1; xPoint = xPoints[i], yPoint = yPoints[i]; i++) {
path.push('L ', xPoint - minX, ' ', yPoint - minY, ' ');
}
path = path.join('');
if (path === "M 0 0 L 0 0 ") {
return;
}
var p = new fabric.Path(path);
p.fill = null;
p.stroke = this.freeDrawingColor;
p.strokeWidth = this.freeDrawingLineWidth;
//Tyson Benson:
//Add these lines to remove borders/controls
p.hasBorders = p.hasControls = false;
//Or add this line to make the path unselectable
p.selectable = false;
this.add(p);
p.set("left", minX + (maxX - minX) / 2).set("top", minY + (maxY - minY) / 2).setCoords();
this.renderAll();
this.fire('path:created', { path: p });
};
I have removed some whitespace and comments for brevity (please refer to fabric.js for these comments).
You can set p.hasBorders = p.hasControls = false;
or p.selectable = false;
. You dont need both.
来源:https://stackoverflow.com/questions/9154005/how-to-remove-borders-and-corners-from-canvas-object-fabric-js