0

I want to make the background of my canvas an image, but not sure how to do it, what I've tried isn't working. I'm also not sure how to make it so the image isn't stretched or squished when the size of the window changes, any help would be appreciated.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>shark?</title>
    <style>
        html, body {
            height: 100%;
            width: 100%;
            margin: 20;
            overflow: hidden;
        }
        .container {
            display: flex;
            flex-direction: column; 
            align-items: center;
            justify-content: center;
            height: 100%;
            width: 100%;
        }
        h1 {
            margin-top: 10px; 
        }
        canvas {
            background-image: url ("c:\background\backg.jpg");
            margin: 50px; 
            flex: 1;
            width: calc(100% - 100px);
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>shark?</h1>
        <canvas></canvas>
    </div>
</body>
</html>
RelCade
  • 19
  • 5
  • 3
    you need to use Javascript Canvas API and attach the canvas to const ctx = canvas.getContext("2d"); and then use drawImage() function to draw the image. – FarrisFahad Jul 09 '23 at 09:57
  • 2
    This will work if you add `object-fit` and `object-position`, though it's not really 'canvas', more a 'every HTML element' thing in this case. As @FarrisFahad if you actually want to use canvas, you will need to learn the context APIs. – somethinghere Jul 09 '23 at 10:02
  • 1
    @FarrisFahad no need, the canvas is transparent – Alexander Nenashev Jul 09 '23 at 22:21
  • 1
    What are you doing else with that ? If you plan on using it only has a placeholder for this image, then you certainly don't need a . If you're already doing something else with that canvas, then it might be a good idea to include the drawing of that image in your drawing process, or maybe it's indeed best to set it just as a background image, but since we don't know what you are doing, we can't tell. – Kaiido Jul 10 '23 at 05:21

1 Answers1

1

You should remove space in url ("...") (should be url("...")).

To make it more adaptive to window resize add this to styles:

canvas {
  ...
  background-size: cover;
  background-position: center;
}

If you also plan to draw something on this canvas and make it also adaptive, you need to

  1. Recalculate and set new width and height for canvas on resize events.
  2. Calculate new coordinates to make drawing behave as needed or use translate/scale methods of context object.
  3. Do not forget about clearRect method on the first line of drawing part.
AG1
  • 171
  • 5