Solution 1 :

Once you go that route everything has to be proportional or relative to the width & height…

See my example below, I’m still drawing a rect like you did with absolute position
But I’m also drawing a circle on the middle of the canvas.

If you are creating a game you will have to make those decisions what is relative and what is not

var canvas = document.getElementById("background");
var c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var background = new Image();
background.src = "https://images.pexels.com/photos/255379/pexels-photo-255379.jpeg";


background.onload = function(){
  var scale = Math.max(canvas.width / background.width, canvas.height / background.height);
  c.drawImage(this, 0, 0, background.width * scale, canvas.height );
  
  // absolute position
  c.fillRect(10, 10, 50, 50);
  
  // fixed position with relative size 
  c.fillRect(10, 80, 1000*scale, 200*scale);
  
  // relative position with fixed radius
  c.arc(canvas.width/2, canvas.height/2, 50, 0, Math.PI*2);
  c.stroke()
}
<canvas id="background">    </canvas>

Maybe look into gaming engines, those could save you a lot of time:
https://github.com/collections/javascript-game-engines

Problem :

i am trying to programm a little html5 canvas game and facing some dificulties with a dynamic background size and positioning of the objects – maybe i have a little mistake in my thinking, but i hope you can help.
here is my code:

var canvas = document.getElementById("background");
var c = canvas.getContext('2d');



canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var background = new Image();
background.src = "https://images.pexels.com/photos/255379/pexels-photo-255379.jpeg";

function scaleToFill(img){
    // get the scale
    var scale = Math.max(canvas.width / background.width, canvas.height / background.height);
    
    c.drawImage(img, 0, 0, background.width * scale, canvas.height );
}


background.onload = function(){
    scaleToFill(this);
    c.fillRect(100, 100, 100, 100);
}
body {
    margin: 0;
    padding: 9;
    width:  100%;
    height: 100%;

}
canvas {
    border:1px solid #000;
}
   <canvas id="background" style="z-index: -1; position:fixed; top:0;left:0;">  
    </canvas>
    

pretty basic – what my code does is try to scale the bg pic to the full height.
Now but because of this scaling every other element, like the test rect i draw is sitting at different positions depending on the screensize.

Does anyone know how i can solve this with a different approach without having a static height and width?
Or is there a js framework that can do this much easier?

By

Leave a Reply

Your email address will not be published. Required fields are marked *