Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
How to set a background color for canvas element?

I need to generate a canvas element that has its own background color and at its center some text that uses a image background:

==================
|                 |
|      Hello      |
|                 |
==================

Right now I can display a text filled with an image

const init = () => {
  const canvas = document.getElementById("canvas")
  const context = canvas.getContext('2d')
  context.font = 'bold 140px Times'
  context.textBaseline = 'center'
  const image = new Image()
  image.src = 'https://img.redbull.com/images/c_crop,x_0,y_0,h_1080,w_1620/c_fill,w_1500,h_1000/q_auto,f_auto/redbullcom/2017/08/29/03820845-b090-444f-86d1-e5259d11482f/most-heroic-pokemon.jpg.jpg'

  image.onload = () => {
    const pattern = context.createPattern(image, null)
    context.fillStyle = pattern
    context.fillText('Lorem ipsum', 0, 200)
  }
}

init()
canvas {
  border: 1px solid #000;
}
<!doctype html>
<html>

<head>
</head>

<body>
  <canvas id="canvas" width="1920" height="1080"></canvas>
</body>

</html>

I know I can change the canvas background using css but I get a transparent png when I save the images using right click.

How can I set a black background for the canvas and set a text with its own background?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The Canvas API defaults to a black transparent background (the imageData.data on an unchanged canvas will be all zeroes where each set of four values indicates RGBA values). You can use fillRect in the Canvas API to set the background color of the whole canvas.

Note: You can set the fillStyle to change the color, but Canvas API defaults to #000 (black) for this property, so you only need to set it explicitly if it has been changed.

const init = () => {
  const canvas = document.getElementById("canvas")
  const context = canvas.getContext('2d')
  context.fillRect(0, 0, canvas.width, canvas.height)
  context.font = 'bold 140px Times'
  context.textBaseline = 'center'
  const image = new Image()
  image.src = 'https://img.redbull.com/images/c_crop,x_0,y_0,h_1080,w_1620/c_fill,w_1500,h_1000/q_auto,f_auto/redbullcom/2017/08/29/03820845-b090-444f-86d1-e5259d11482f/most-heroic-pokemon.jpg.jpg'

  image.onload = () => {
    const pattern = context.createPattern(image, null)
    context.fillStyle = pattern
    context.textAlign = "center"
    context.fillText('Lorem ipsum', canvas.width / 2, canvas.height / 2)
  }
}

init()
canvas {
  border: 1px solid #000;
}
<!doctype html>
<html>

<head>
</head>

<body>
  <canvas id="canvas" width="1920" height="1080"></canvas>
</body>

</html>

EDIT

Thank you to Roko for alerting me to the centering requirement of the question.

I made a few changes to my code to include horizontal and vertical alignment

Horizontal

        context.textAlign = "center"

Vertical

  // already implemented in your code
  context.textBaseline = 'center'

Using fillText to center the text fully with the above settings applied

    context.fillText('Lorem ipsum', canvas.width / 2, canvas.height / 2)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda