简体   繁体   English

HTML5 Canvas - 正确调整元素大小

[英]HTML5 Canvas - Resize elements correctly

I currently have a canvas container with a width of 100% width and 50% height.我目前有一个宽度为 100% 宽度和 50% 高度的 canvas 容器。 Whenever I draw something like lines, I have to pass x and y coordinates to it:每当我画线之类的东西时,我必须将 x 和 y 坐标传递给它:

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:不幸的是,每当我调整 canvas 的大小(通过调整浏览器的大小)时,该行仍然具有与以前相同的尺寸,并且不会调整到它的 canvas 大小,如图所示: 在此处输入图像描述

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.我也想过计算 x 和 y 位置,但我不知道最大坐标。 Or are there any better ways?或者有没有更好的方法? Later, it I'm planning to add rectangles, input fields, and so on...稍后,我打算添加矩形、输入字段等...

Thank you for helping!感谢您的帮助!

context.moveTo and context.lineTo takes in a number of pixels, so if you do not change the value the distance will not change. context.moveTocontext.lineTo接受多个像素,所以如果你不改变值,距离不会改变。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM