首页 > 解决方案 > HTML5 Canvas - 正确调整元素大小

问题描述

我目前有一个宽度为 100% 宽度和 50% 高度的画布容器。每当我画线之类的东西时,我必须将 x 和 y 坐标传递给它:

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

不幸的是,每当我调整画布的大小(通过调整浏览器的大小)时,这条线仍然具有与以前相同的尺寸,并且不会调整到它的画布大小,如图所示: 在此处输入图像描述

这就是我实际调整大小的方式:

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();

有谁知道如何解决这个问题?我也想过计算 x 和 y 位置,但我不知道最大坐标。或者有没有更好的方法?稍后,我打算添加矩形、输入字段等...

感谢您的帮助!

标签: javascripthtmlcsscanvas

解决方案


context.moveTocontext.lineTo接受多个像素,因此如果您不更改该值,则距离不会改变。您可以改为使用画布宽度的百分比:

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();

推荐阅读