javascript - 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 位置,但我不知道最大坐标。或者有没有更好的方法?稍后,我打算添加矩形、输入字段等...
感谢您的帮助!
解决方案
context.moveTo
并context.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();
推荐阅读
- javascript - JWT API 令牌存储
- angular - 如何使用 Angular 5.0 在高库存蜡烛棒图中添加指标?
- regex - DataFrame 中包含子字符串的行数
- bash - 将循环下载的文件链接到带有 bash 循环的文本列表中的标识符
- javascript - 如何结合css旋转?
- ios - 应用程序在第二次呈现视图(弹出框)时崩溃
- java - 从postgresql读取数据时无法在flink中获取Json数据
- firebase - 我们应该怎么做才能动态获取在 dialogflow 中输入的名称并将其存储在 firestore 中?
- android - 将图像文件转换为 base 64 需要更多时间
- caffe - 在 mac OS 上安装 Caffe 时出错