简体   繁体   中英

Fit rect() around text() width

I am using p5.js for something and I need to have text inside rectangles appearing at the top of my canvas. I want this text to force the rect() around it to fit so that there is no empty space of the rectangle, it just wraps around the string. Previously I tried giving the rectangle dimensions manually, though this worked poorly depending on the length of the string. I have looked at using HTML5's canvas 'measureText' and 'fillText' functions, though these work only for the html canvas, not the javascript canvas I have loaded a background image onto.

I want to have the coloured rectangle fit around the text, on the JS canvas as below. JS background image canvas with rectangle

With the following code:

function word (x) {
this.wordX = x;
this.wordY = random(5,30);

this.display = function(){
    fill('#4545f5');
    rect(this.wordX,this.wordY,420,55);
    fill('#ffffff');
    textSize(25);
    text("alphabet", this.wordX+5, this.wordY+10, 410, 55); 
}

What can I use to make the box fit neatly around the text and still use the JS background canvas, or can I put an image from a file onto the HTML canvas? Following is the setup() code for instantiation and canvas drawing:

function preload() { 
    BG = loadImage('images/background.PNG'); 
}

function setup() {
    createCanvas(windowWidth,windowHeight);
    word1 = new word(random(10,windowWidth-370));
}

function draw() {
  image(BG, 0, 0, windowWidth, windowHeight);

  word1.display();
}

This code demonstrates using measureText() on a canvas context created with createCanvas()

const element = createCanvas(300, 400);
const context = element.getContext('2d');

context.font = `22px sans-serif`;
console.log(context.measureText('hello world').width);

context.font = `22px cursive`;
console.log(context.measureText('hello world').width);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM