【问题标题】:Why are there 2 diffrent Sizes of a HTML Canvas? [duplicate]为什么有 2 种不同尺寸的 HTML 画布? [复制]
【发布时间】:2020-02-25 05:09:45
【问题描述】:

我目前正在处理一个 HTML/Javascript 项目,我正在使用 HTML Canvas 和 Context2D 进行绘图。 或多或少,我正在绘制没有固定瓷砖大小的 2d 世界的一部分。

let width = canvas.width;
let height = canvas.height;
let cellHeight = height/rows * viewSizeMultiplier.y,cellWidth = width/columns * viewSizeMultiplier.x;

viewSizeMultiplier 相当于地图上 8 个 Tiles 的 1/8。在单击 Canvas 时,我通过获取特定的 Tile 遇到了很多困难,因为 canvas.size 不会通过调整窗口大小来调整自身。

.canvas { 
   width: 60%;
   height: 80%;
   left:5%;
   top:10%;
}

这就是我在 css 中实现我的画布的方式。为了在我的屏幕上获取当前的 Tile,我必须像这样计算不同尺寸的纵横比:

function  getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect(),
        scaleX = canvas.width / rect.width,
        scaleY = canvas.height / rect.height; 

    return {
      x: (evt.clientX - rect.left) * scaleX,   
      y: (evt.clientY - rect.top) * scaleY    
    }
  }

所以我的问题是为什么有 2 种不同尺寸的画布?如果它使用 canvas.size 大小,它会调整它的分辨率吗?

添加片段:

let canvas = document.getElementsByClassName('canvas')[0];
const canvasWidth= canvas.width;
const actualWidth =canvas.getBoundingClientRect().width;
console.log(canvasWidth,actualWidth);//300 , 522

【问题讨论】:

  • 请创建 sn-p 示例。对于canvas2d来说很简单。然后你会得到快速的答复。

标签: javascript html css canvas


【解决方案1】:

CSS 样式在画布首次创建后不会更改其像素尺寸。您需要专门设置 canvas.widthcanvas.height 为新尺寸以更改画布的像素大小,否则您最终只会得到原始宽度 * 高度像素缩放到不同尺寸。

您需要监听调整大小事件以了解何时更改画布的尺寸。

【讨论】:

  • 哇,感谢您的快速回答。我的渲染函数中的这段代码修复了分辨率问题if(canvas.getBoundingClientRect().width != canvas.width){ canvas.width = canvas.getBoundingClientRect().width; } if(canvas.getBoundingClientRect().height != canvas.height){ canvas.height = canvas.getBoundingClientRect().height; }
【解决方案2】:

好吧,画布的内部尺寸可以与画布 DOM 元素的尺寸不同。

canvas.width 为您提供画布 inner 宽度,而 rect.width 仅为您提供画布 DOM 元素的 outer 宽度,不包括已绘制的画布的任何部分超出外部宽度,需要滚动才能到达。身高也是如此。

因此,简而言之,当您需要滚动查看画布中的所有内容时,这意味着画布的内部尺寸大于其外部尺寸。

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 2021-12-21
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    相关资源
    最近更新 更多