Implement text rendering along paths

This commit also changes the TextReplay.drawText() signature, and moves
geometry calculation into drawText(). This improves performance where no
text needs to be rendered (TextStyle.getText() == ''), which is used often
in applications.
This commit is contained in:
Andreas Hocevar
2017-09-07 23:32:31 +02:00
parent 37dcd79a86
commit efc86d59b0
12 changed files with 640 additions and 189 deletions

View File

@@ -2,12 +2,15 @@ goog.provide('ol.render.canvas.TextReplay');
goog.require('ol');
goog.require('ol.colorlike');
goog.require('ol.dom');
goog.require('ol.geom.GeometryType');
goog.require('ol.has');
goog.require('ol.render.canvas');
goog.require('ol.render.canvas.Instruction');
goog.require('ol.render.canvas.Replay');
goog.require('ol.render.replay');
goog.require('ol.structs.LRUCache');
goog.require('ol.style.TextPlacement');
/**
@@ -24,6 +27,12 @@ ol.render.canvas.TextReplay = function(tolerance, maxExtent, resolution, pixelRa
ol.render.canvas.Replay.call(this, tolerance, maxExtent, resolution, pixelRatio, overlaps);
/**
* @private
* @type {Array.<HTMLCanvasElement>}
*/
this.labels_ = null;
/**
* @private
* @type {string}
@@ -78,6 +87,24 @@ ol.render.canvas.TextReplay = function(tolerance, maxExtent, resolution, pixelRa
*/
this.textState_ = null;
/**
* @private
* @type {string}
*/
this.textKey_ = '';
/**
* @private
* @type {string}
*/
this.fillKey_ = '';
/**
* @private
* @type {string}
*/
this.strokeKey_ = '';
while (ol.render.canvas.TextReplay.labelCache_.canExpireCache()) {
ol.render.canvas.TextReplay.labelCache_.pop();
}
@@ -95,33 +122,65 @@ ol.render.canvas.TextReplay.labelCache_ = new ol.structs.LRUCache();
/**
* @param {string} font Font to use for measuring.
* @param {Array.<string>} lines Lines to measure.
* @param {Array.<number>} widths Array will be populated with the widths of
* each line.
* @return {ol.Size} Measuremnt.
* @return {ol.Size} Measurement.
*/
ol.render.canvas.TextReplay.measureText = (function() {
ol.render.canvas.TextReplay.measureTextHeight = (function() {
var textContainer;
return function(font, lines, widths) {
if (!textContainer) {
textContainer = document.createElement('span');
textContainer.textContent = 'M';
textContainer.style.visibility = 'hidden';
textContainer.style.whiteSpace = 'nowrap';
}
textContainer.style.font = font;
document.body.appendChild(textContainer);
var height = textContainer.offsetHeight;
document.body.removeChild(textContainer);
return height;
};
})();
/**
* @this {Object}
* @param {CanvasRenderingContext2D} context Context.
* @param {number} pixelRatio Pixel ratio.
* @param {string} text Text.
* @return {number} Width.
*/
ol.render.canvas.TextReplay.getTextWidth = function(context, pixelRatio, text) {
var width = this[text];
if (!width) {
this[text] = width = context.measureText(text).width;
}
return width * pixelRatio;
};
/**
* @param {string} font Font to use for measuring.
* @param {Array.<string>} lines Lines to measure.
* @param {Array.<number>} widths Array will be populated with the widths of
* each line.
* @return {number} Width of the whole text.
*/
ol.render.canvas.TextReplay.measureTextWidths = (function() {
var context;
return function(font, lines, widths) {
if (!context) {
context = ol.dom.createCanvasContext2D(1, 1);
}
context.font = font;
var numLines = lines.length;
var width = 0;
var currentWidth, i;
for (i = 0; i < numLines; ++i) {
textContainer.textContent = lines[i];
currentWidth = textContainer.offsetWidth;
currentWidth = context.measureText(lines[i]).width;
width = Math.max(width, currentWidth);
widths.push(currentWidth);
}
var measurement = [width, textContainer.offsetHeight * numLines];
document.body.removeChild(textContainer);
return measurement;
return width;
};
})();
@@ -129,51 +188,113 @@ ol.render.canvas.TextReplay.measureText = (function() {
/**
* @inheritDoc
*/
ol.render.canvas.TextReplay.prototype.drawText = function(flatCoordinates, offset, end, stride, geometry, feature) {
ol.render.canvas.TextReplay.prototype.drawText = function(geometry, feature) {
var fillState = this.textFillState_;
var strokeState = this.textStrokeState_;
var textState = this.textState_;
if (this.text_ === '' || !textState || (!fillState && !strokeState)) {
if (this.text_ === '' || !this.textState_ || (!fillState && !strokeState)) {
return;
}
this.beginGeometry(geometry, feature);
var begin = this.coordinates.length;
var myBegin = this.coordinates.length;
var myEnd =
this.appendFlatCoordinates(flatCoordinates, offset, end, stride, false, false);
var fill = !!fillState;
var stroke = !!strokeState;
var pixelRatio = this.pixelRatio;
var textAlign = textState.textAlign;
var align = ol.render.replay.TEXT_ALIGN[textAlign];
var textBaseline = textState.textBaseline;
var baseline = ol.render.replay.TEXT_ALIGN[textBaseline];
var strokeWidth = stroke && strokeState.lineWidth ? strokeState.lineWidth : 0;
var geometryType = geometry.getType();
var flatCoordinates = null;
var end = 2;
var stride = 2;
if (this.textState_.placement === ol.style.TextPlacement.LINE) {
var ends;
flatCoordinates = geometry.getFlatCoordinates();
stride = geometry.getStride();
if (geometryType == ol.geom.GeometryType.LINE_STRING) {
ends = [flatCoordinates.length];
} else if (geometryType == ol.geom.GeometryType.MULTI_LINE_STRING) {
ends = geometry.getEnds();
} else if (geometryType == ol.geom.GeometryType.POLYGON) {
ends = geometry.getEnds().slice(0, 1);
} else if (geometryType == ol.geom.GeometryType.MULTI_POLYGON) {
var endss = geometry.getEndss();
ends = [];
for (var i = 0, ii = endss.length; i < ii; ++i) {
ends.push(endss[i][0]);
}
}
var flatOffset = 0;
var flatEnd;
for (var o = 0, oo = ends.length; o < oo; ++o) {
flatEnd = ends[o];
end = this.appendFlatCoordinates(flatCoordinates, flatOffset, flatEnd, stride, false, false);
flatOffset = flatEnd;
this.drawChars_(begin, end);
begin = end;
}
} else {
switch (geometryType) {
case ol.geom.GeometryType.POINT:
case ol.geom.GeometryType.MULTI_POINT:
flatCoordinates = geometry.getFlatCoordinates();
end = flatCoordinates.length;
break;
case ol.geom.GeometryType.LINE_STRING:
flatCoordinates = /** @type {ol.geom.LineString} */ (geometry).getFlatMidpoint();
break;
case ol.geom.GeometryType.CIRCLE:
flatCoordinates = /** @type {ol.geom.Circle} */ (geometry).getCenter();
break;
case ol.geom.GeometryType.MULTI_LINE_STRING:
flatCoordinates = /** @type {ol.geom.MultiLineString} */ (geometry).getFlatMidpoints();
end = flatCoordinates.length;
break;
case ol.geom.GeometryType.POLYGON:
flatCoordinates = /** @type {ol.geom.Polygon} */ (geometry).getFlatInteriorPoint();
break;
case ol.geom.GeometryType.MULTI_POLYGON:
flatCoordinates = /** @type {ol.geom.MultiPolygon} */ (geometry).getFlatInteriorPoints();
end = flatCoordinates.length;
break;
default:
}
end = this.appendFlatCoordinates(flatCoordinates, 0, end, stride, false, false);
this.drawTextImage_(begin, end);
}
this.endGeometry(geometry, feature);
};
/**
* @private
* @param {string} text Text.
* @param {boolean} fill Fill.
* @param {boolean} stroke Stroke.
* @return {HTMLCanvasElement} Image.
*/
ol.render.canvas.TextReplay.prototype.getImage_ = function(text, fill, stroke) {
var label;
var text = this.text_;
var key =
(stroke ?
(typeof strokeState.strokeStyle == 'string' ? strokeState.strokeStyle : ol.getUid(strokeState.strokeStyle)) +
strokeState.lineCap + strokeState.lineDashOffset + '|' + strokeWidth +
strokeState.lineJoin + strokeState.miterLimit +
'[' + strokeState.lineDash.join() + ']' : '') +
textState.font + textAlign + text +
(fill ?
(typeof fillState.fillStyle == 'string' ? fillState.fillStyle : ('|' + ol.getUid(fillState.fillStyle))) : '');
var key = (stroke ? this.strokeKey_ : '') + this.textKey_ + text + (fill ? this.fillKey_ : '');
var lines = text.split('\n');
var numLines = lines.length;
if (!ol.render.canvas.TextReplay.labelCache_.containsKey(key)) {
label = /** @type {HTMLCanvasElement} */ (document.createElement('canvas'));
ol.render.canvas.TextReplay.labelCache_.set(key, label);
var context = label.getContext('2d');
var strokeState = this.textStrokeState_;
var fillState = this.textFillState_;
var textState = this.textState_;
var pixelRatio = this.pixelRatio;
var align = ol.render.replay.TEXT_ALIGN[textState.textAlign];
var strokeWidth = stroke && strokeState.lineWidth ? strokeState.lineWidth : 0;
var widths = [];
var metrics = ol.render.canvas.TextReplay.measureText(textState.font, lines, widths);
var lineHeight = metrics[1] / numLines;
label.width = Math.ceil(metrics[0] + 2 * strokeWidth) * pixelRatio;
label.height = Math.ceil(metrics[1] + 2 * strokeWidth) * pixelRatio;
var width = ol.render.canvas.TextReplay.measureTextWidths(textState.font, lines, widths);
var lineHeight = ol.render.canvas.TextReplay.measureTextHeight(textState.font);
var height = lineHeight * numLines;
var renderWidth = (width + 2 * strokeWidth);
var context = ol.dom.createCanvasContext2D(
Math.ceil(renderWidth * pixelRatio),
Math.ceil((height + 2 * strokeWidth) * pixelRatio));
label = context.canvas;
ol.render.canvas.TextReplay.labelCache_.set(key, label);
context.scale(pixelRatio, pixelRatio);
context.font = textState.font;
if (stroke) {
@@ -191,39 +312,101 @@ ol.render.canvas.TextReplay.prototype.drawText = function(flatCoordinates, offse
context.fillStyle = fillState.fillStyle;
}
context.textBaseline = 'top';
context.textAlign = 'left';
var x = align * label.width / pixelRatio + 2 * (0.5 - align) * strokeWidth;
context.textAlign = 'center';
var leftRight = (0.5 - align);
var x = align * label.width / pixelRatio + leftRight * 2 * strokeWidth;
var i;
if (stroke) {
for (i = 0; i < numLines; ++i) {
context.strokeText(lines[i], x - align * widths[i], strokeWidth + i * lineHeight);
context.strokeText(lines[i], x + leftRight * widths[i], strokeWidth + i * lineHeight);
}
}
if (fill) {
for (i = 0; i < numLines; ++i) {
context.fillText(lines[i], x - align * widths[i], strokeWidth + i * lineHeight);
context.fillText(lines[i], x + leftRight * widths[i], strokeWidth + i * lineHeight);
}
}
}
label = ol.render.canvas.TextReplay.labelCache_.get(key);
return ol.render.canvas.TextReplay.labelCache_.get(key);
};
/**
* @private
* @param {number} begin Begin.
* @param {number} end End.
*/
ol.render.canvas.TextReplay.prototype.drawTextImage_ = function(begin, end) {
var textState = this.textState_;
var strokeState = this.textStrokeState_;
var pixelRatio = this.pixelRatio;
var align = ol.render.replay.TEXT_ALIGN[textState.textAlign];
var baseline = ol.render.replay.TEXT_ALIGN[textState.textBaseline];
var strokeWidth = strokeState && strokeState.lineWidth ? strokeState.lineWidth : 0;
var label = this.getImage_(this.text_, !!this.textFillState_, !!this.textStrokeState_);
var anchorX = align * label.width / pixelRatio + 2 * (0.5 - align) * strokeWidth;
var anchorY = baseline * label.height / pixelRatio + 2 * (0.5 - baseline) * strokeWidth;
this.instructions.push([
ol.render.canvas.Instruction.DRAW_IMAGE, myBegin, myEnd, label,
(anchorX - this.textOffsetX_) * pixelRatio, (anchorY - this.textOffsetY_) * pixelRatio,
this.instructions.push([ol.render.canvas.Instruction.DRAW_IMAGE, begin, end,
label, (anchorX - this.textOffsetX_) * pixelRatio, (anchorY - this.textOffsetY_) * pixelRatio,
label.height, 1, 0, 0, this.textRotateWithView_, this.textRotation_,
this.textScale_, true, label.width
]);
this.hitDetectionInstructions.push([
ol.render.canvas.Instruction.DRAW_IMAGE, myBegin, myEnd, label,
(anchorX - this.textOffsetX_) * pixelRatio, (anchorY - this.textOffsetY_) * pixelRatio,
this.hitDetectionInstructions.push([ol.render.canvas.Instruction.DRAW_IMAGE, begin, end,
label, (anchorX - this.textOffsetX_) * pixelRatio, (anchorY - this.textOffsetY_) * pixelRatio,
label.height, 1, 0, 0, this.textRotateWithView_, this.textRotation_,
this.textScale_ / pixelRatio, true, label.width
]);
};
this.endGeometry(geometry, feature);
/**
* @private
* @param {number} begin Begin.
* @param {number} end End.
*/
ol.render.canvas.TextReplay.prototype.drawChars_ = function(begin, end) {
var pixelRatio = this.pixelRatio;
var strokeState = this.textStrokeState_;
var fill = !!this.textFillState_;
var stroke = !!strokeState;
var textState = this.textState_;
var baseline = ol.render.replay.TEXT_ALIGN[textState.textBaseline];
var strokeWidth = stroke && strokeState.lineWidth ? strokeState.lineWidth * pixelRatio : 0;
var labels = [];
var text = this.text_;
var numChars = this.text_.length;
var i;
if (stroke) {
for (i = 0; i < numChars; ++i) {
labels.push(this.getImage_(text.charAt(i), false, stroke));
}
}
if (fill) {
for (i = 0; i < numChars; ++i) {
labels.push(this.getImage_(text.charAt(i), fill, false));
}
}
var context = labels[0].getContext('2d');
var offsetY = this.textOffsetY_ * pixelRatio;
var align = ol.render.replay.TEXT_ALIGN[textState.textAlign || ol.render.canvas.defaultTextAlign];
var widths = {};
this.instructions.push([ol.render.canvas.Instruction.DRAW_CHARS,
begin, end, labels, baseline,
textState.exceedLength, textState.maxAngle,
ol.render.canvas.TextReplay.getTextWidth.bind(widths, context, pixelRatio),
offsetY, strokeWidth, this.text_, align, this.textScale_
]);
this.hitDetectionInstructions.push([ol.render.canvas.Instruction.DRAW_CHARS,
begin, end, labels, baseline,
textState.exceedLength, textState.maxAngle,
ol.render.canvas.TextReplay.getTextWidth.bind(widths, context, 1),
offsetY, strokeWidth, this.text_, align, this.textScale_ / pixelRatio
]);
};
@@ -231,28 +414,26 @@ ol.render.canvas.TextReplay.prototype.drawText = function(flatCoordinates, offse
* @inheritDoc
*/
ol.render.canvas.TextReplay.prototype.setTextStyle = function(textStyle) {
var textState, fillState, strokeState;
if (!textStyle) {
this.text_ = '';
} else {
var textFillStyle = textStyle.getFill();
if (!textFillStyle) {
this.textFillState_ = null;
fillState = this.textFillState_ = null;
} else {
var textFillStyleColor = textFillStyle.getColor();
var fillStyle = ol.colorlike.asColorLike(textFillStyleColor ?
textFillStyleColor : ol.render.canvas.defaultFillStyle);
if (!this.textFillState_) {
this.textFillState_ = {
fillStyle: fillStyle
};
} else {
var textFillState = this.textFillState_;
textFillState.fillStyle = fillStyle;
fillState = this.textFillState_;
if (!fillState) {
fillState = this.textFillState_ = /** @type {ol.CanvasFillState} */ ({});
}
fillState.fillStyle = fillStyle;
}
var textStrokeStyle = textStyle.getStroke();
if (!textStrokeStyle) {
this.textStrokeState_ = null;
strokeState = this.textStrokeState_ = null;
} else {
var textStrokeStyleColor = textStrokeStyle.getColor();
var textStrokeStyleLineCap = textStrokeStyle.getLineCap();
@@ -275,26 +456,17 @@ ol.render.canvas.TextReplay.prototype.setTextStyle = function(textStyle) {
textStrokeStyleMiterLimit : ol.render.canvas.defaultMiterLimit;
var strokeStyle = ol.colorlike.asColorLike(textStrokeStyleColor ?
textStrokeStyleColor : ol.render.canvas.defaultStrokeStyle);
if (!this.textStrokeState_) {
this.textStrokeState_ = {
lineCap: lineCap,
lineDash: lineDash,
lineDashOffset: lineDashOffset,
lineJoin: lineJoin,
lineWidth: lineWidth,
miterLimit: miterLimit,
strokeStyle: strokeStyle
};
} else {
var textStrokeState = this.textStrokeState_;
textStrokeState.lineCap = lineCap;
textStrokeState.lineDash = lineDash;
textStrokeState.lineDashOffset = lineDashOffset;
textStrokeState.lineJoin = lineJoin;
textStrokeState.lineWidth = lineWidth;
textStrokeState.miterLimit = miterLimit;
textStrokeState.strokeStyle = strokeStyle;
strokeState = this.textStrokeState_;
if (!strokeState) {
strokeState = this.textStrokeState_ = /** @type {ol.CanvasStrokeState} */ ({});
}
strokeState.lineCap = lineCap;
strokeState.lineDash = lineDash;
strokeState.lineDashOffset = lineDashOffset;
strokeState.lineJoin = lineJoin;
strokeState.lineWidth = lineWidth;
strokeState.miterLimit = miterLimit;
strokeState.strokeStyle = strokeStyle;
}
var textFont = textStyle.getFont();
var textOffsetX = textStyle.getOffsetX();
@@ -311,23 +483,32 @@ ol.render.canvas.TextReplay.prototype.setTextStyle = function(textStyle) {
textTextAlign : ol.render.canvas.defaultTextAlign;
var textBaseline = textTextBaseline !== undefined ?
textTextBaseline : ol.render.canvas.defaultTextBaseline;
if (!this.textState_) {
this.textState_ = {
font: font,
textAlign: textAlign,
textBaseline: textBaseline
};
} else {
var textState = this.textState_;
textState.font = font;
textState.textAlign = textAlign;
textState.textBaseline = textBaseline;
textState = this.textState_;
if (!textState) {
textState = this.textState_ = /** @type {ol.CanvasTextState} */ ({});
}
textState.exceedLength = textStyle.getExceedLength();
textState.font = font;
textState.maxAngle = textStyle.getMaxAngle();
textState.placement = textStyle.getPlacement();
textState.textAlign = textAlign;
textState.textBaseline = textBaseline;
this.text_ = textText !== undefined ? textText : '';
this.textOffsetX_ = textOffsetX !== undefined ? textOffsetX : 0;
this.textOffsetY_ = textOffsetY !== undefined ? textOffsetY : 0;
this.textRotateWithView_ = textRotateWithView !== undefined ? textRotateWithView : false;
this.textRotation_ = textRotation !== undefined ? textRotation : 0;
this.textScale_ = textScale !== undefined ? textScale : 1;
this.strokeKey_ = strokeState ?
(typeof strokeState.strokeStyle == 'string' ? strokeState.strokeStyle : ol.getUid(strokeState.strokeStyle)) +
strokeState.lineCap + strokeState.lineDashOffset + '|' + strokeState.lineWidth +
strokeState.lineJoin + strokeState.miterLimit + '[' + strokeState.lineDash.join() + ']' :
'';
this.textKey_ = textState.font + textState.textAlign;
this.fillKey_ = fillState ?
(typeof fillState.fillStyle == 'string' ? fillState.fillStyle : ('|' + ol.getUid(fillState.fillStyle))) :
'';
}
};