为了在不同分辨率的屏幕上正确显示光标图像并获取其在画布上的位置,需要进行以下步骤:
const screenWidth = window.screen.width;
const screenHeight = window.screen.height;
const devicePixelRatio = window.devicePixelRatio || 1;
const canvas = document.getElementById('canvas'); // 画布元素
canvas.width = screenWidth * devicePixelRatio; // 在画布元素上设置实际宽高
canvas.height = screenHeight * devicePixelRatio;
canvas {
width: screenWidthpx;
height: screenHeightpx;
transform: scale(1/设备像素比); // 将画布缩小回常规大小
}
function draw() {
const mouseX = event.clientX * devicePixelRatio;
const mouseY = event.clientY * devicePixelRatio;
// 绘制光标图像
ctx.drawImage(cursorImage, mouseX, mouseY);
}