Pinnokkio
Pinnokkio

Reputation: 549

HTML5 Canvas - Resize elements correctly

I currently have a canvas container with a width of 100% width and 50% height. Whenever I draw something like lines, I have to pass x and y coordinates to it:

context.moveTo(20, 20);
context.lineTo(50, 20);
context.stroke();

Unfortunately, whenever I resize the canvas (by resizing the browser), the line still have the same dimension as before and will not adjust to it's canvas size like seen in the picture: enter image description here

This is how I actually resize:

var scale = window.devicePixelRatio;

this.canvas.width = Math.floor(parseInt(this.$canvasPage.css('width')) * scale);
this.canvas.height = Math.floor(parseInt(this.$canvasPage.css('height')) * scale);
this.context.scale(scale, scale);

this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.drawContent();

Does anyone have an idea how to fix this? I also thought about something like calculating x and y positions but I do not know the maximum coordinates. Or are there any better ways? Later, it I'm planning to add rectangles, input fields, and so on...

Thank you for helping!

Upvotes: 0

Views: 60

Answers (1)

Viktor W
Viktor W

Reputation: 1149

context.moveTo and context.lineTo takes in a number of pixels, so if you do not change the value the distance will not change. You could instead use a percentage of the canvases width:

context.moveTo(0.2 * this.canvas.width, 0.2 * this.canvas.height);
context.lineTo(0.5 * this.canvas.width, 0.2 * this.canvas.height);
context.stroke();

Upvotes: 2

Related Questions