【发布时间】: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