Home > Software engineering >  Difference in Behavior Between Firefox and Chrome for HTML Canvas fillRect operation and fontBoundin
Difference in Behavior Between Firefox and Chrome for HTML Canvas fillRect operation and fontBoundin

Time:11-20

I am working on a bug in a library for Leaflet and I cannot figure out how to work around a difference in how Firefox and Chrome implement HTML Canvas. It revolves around the ctx.fillRect function -- it does not appear to be working in Firefox. On Chrome, the application works properly and the labels are properly coloured:

Chrome

However with Firefox it appears as such:

Firefox

The code in my library which draws the labels is:

  drawLabel(labelText, textColor, backgroundColor, labelPosition) {
    const textWidth = this.ctx.measureText(labelText).width;
    const textHeight = this.ctx.measureText(labelText).fontBoundingBoxAscent;

    // Calculate label xy position
    const labelX = labelPosition.x;
    const labelY = labelPosition.y;
    this.ctx.fillStyle = backgroundColor;
    // Magic numbers will centre the rectangle over the text
    this.ctx.fillRect(labelX - textWidth / 2 - 1, labelY - textHeight   1, textWidth   3, textHeight   2);
    this.ctx.fillStyle = textColor;
    this.ctx.fillText(labelText, labelX - textWidth / 2, labelY);
  }

I've tried to leverage ctx.rect and ctx.fill as a substitute but that does not work. Logging the ctx object did show that Chrome and Firefox implement Canvas context a little differently, but the fields that I am modifying do not appear to be different.

CodePudding user response:

The problem is that fontBoundingBoxAscent is not enabled in Firefox by default and requires the user to turn it on in about:config under dom.textMetrics.fontBoundingBox.enabled.

  • Related