天天看點

three,js項目開發總結 - 建立精靈字型

makeTextSprite(message, parameters) {
  if (parameters === undefined) parameters = {}
  var fontface = parameters.hasOwnProperty("fontface") ? parameters["fontface"] : "Arial"
  /* 字型大小 */
  var fontsize = parameters.hasOwnProperty("fontsize") ? parameters["fontsize"] : 18
  /* 邊框厚度 */
  var borderThickness = parameters.hasOwnProperty("borderThickness") ? parameters["borderThickness"] : 5
  /* 邊框顔色 */
  var borderColor = parameters.hasOwnProperty("borderColor") ? parameters["borderColor"] : {
    r: 0,
    g: 0,
    b: 0,
    a: 1.0
  }
  /* 背景顔色 */
  var backgroundColor = parameters.hasOwnProperty("backgroundColor") ? parameters["backgroundColor"] : {
    r: 255,
    g: 255,
    b: 255,
    a: 1.0
  }
  /* 建立畫布 */
  var canvas = document.createElement('canvas')
  var context = canvas.getContext('2d')
  /* 字型加粗 */
  context.font = "Bold " + fontsize + "px " + fontface
  /* 擷取文字的大小資料,高度取決于文字的大小 */
  var metrics = context.measureText(message)
  var textWidth = metrics.width
  /* 背景顔色 */
  context.fillStyle = "rgba(" + backgroundColor.r + "," + backgroundColor.g + "," + backgroundColor.b + "," +
    backgroundColor.a + ")"
  /* 邊框的顔色 */
  context.strokeStyle = "rgba(" + borderColor.r + "," + borderColor.g + "," + borderColor.b + "," + borderColor
    .a + ")"
  context.lineWidth = borderThickness
  /* 繪制圓角矩形 */
  this.roundRect(context, borderThickness / 2, borderThickness / 2, textWidth + borderThickness, fontsize * 1.4 +
    borderThickness, 6)
  /* 字型顔色 */
  context.fillStyle = "rgba(0, 0, 0, 1.0)"
  context.fillText(message, borderThickness, fontsize + borderThickness)
  /* 畫布内容用于紋理貼圖 */
  var texture = new THREE.Texture(canvas)
  texture.needsUpdate = true
  var spriteMaterial = new THREE.SpriteMaterial({
    map: texture
  })
  var sprite = new THREE.Sprite(spriteMaterial)
  /* 縮放比例 */
  sprite.scale.set(10, 5, 0)
  return sprite
}
           

繼續閱讀