Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference in Behavior Between Firefox and Chrome for HTML Canvas fillRect operation

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading