Reputation: 639
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?
Upvotes: 2
Views: 3317
Reputation: 2279
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>
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)
Upvotes: 3