【问题标题】:HTML5 Canvas - Resize elements correctlyHTML5 Canvas - 正确调整元素大小
【发布时间】:2021-04-17 00:16:51
【问题描述】:

我目前有一个宽度为 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 位置,但我不知道最大坐标。或者有没有更好的方法? 之后,我打算添加矩形、输入框等等……

感谢您的帮助!

【问题讨论】:

    标签: javascript html css canvas


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-31
      • 2013-04-14
      • 1970-01-01
      • 2012-12-05
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多