3

im currently working on a HTML/Javascript Project where i am using a HTML Canvas and the Context2D for drawing. More or less i'm drawing a part of a 2d world with no fixed tile size.

let width = canvas.width;
let height = canvas.height;
let cellHeight = height/rows * viewSizeMultiplier.y,cellWidth = width/columns * viewSizeMultiplier.x;

The viewSizeMultiplier is like 1/8 for 8 Tiles on the Map. I've struggeld alot by getting a specific Tile when clicking on the Canvas because the canvas.size does not adjust itself by resizing the window.

.canvas { 
   width: 60%;
   height: 80%;
   left:5%;
   top:10%;
}

That's the way i implemented my canvas in css. For getting the current Tile on my screen i had to calculate the aspect ratio of the diffrent sizes like that:

function  getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect(),
        scaleX = canvas.width / rect.width,
        scaleY = canvas.height / rect.height; 

    return {
      x: (evt.clientX - rect.left) * scaleX,   
      y: (evt.clientY - rect.top) * scaleY    
    }
  }

So my question is why are there 2 diffrent Sizes of the Canvas? If it uses the canvas.size Size does it adjusts its resolution?

Added Snippet :

let canvas = document.getElementsByClassName('canvas')[0];
const canvasWidth= canvas.width;
const actualWidth =canvas.getBoundingClientRect().width;
console.log(canvasWidth,actualWidth);//300 , 522
Jonas Re
  • 93
  • 1
  • 1
  • 10

2 Answers2

2

The CSS styling won't change the pixel dimensions of the canvas after it's first been created. You need to specifically set canvas.width and canvas.height to new dimensions to change the pixel size of the canvas, otherwise you'll end up with nothing more than the original width * height pixels scaled to different sizes.

You'll need to listen for resize events to know when to change the dimensions of the canvas.

kshetline
  • 12,547
  • 4
  • 37
  • 73
  • 1
    Wow Thank You for your quick answer. This Code in my render function fixed the resolution problem ```if(canvas.getBoundingClientRect().width != canvas.width){ canvas.width = canvas.getBoundingClientRect().width; } if(canvas.getBoundingClientRect().height != canvas.height){ canvas.height = canvas.getBoundingClientRect().height; }``` – Jonas Re Oct 29 '19 at 22:59
1

Well, the canvas' inner dimensions can be different from the canvas DOM element's dimensions.

canvas.width gives you the canvas inner width, while rect.width only gives you the canvas DOM element's outer width, excluding any portion of the canvas that is drawn beyond the outer width, and that needs scrolling to reach. The same applies for height.

So, in short, whenever you need to scroll to see all your content in a canvas, this implies that your canvas' inner dimensions is larger than its outer dimensions.

Anis R.
  • 6,656
  • 2
  • 15
  • 37