+
81
-

回答

在 UniApp 中,如果你希望在屏幕上全屏显示一个宽度超过屏幕宽度的 Canvas,同时保持画布的实际像素不压缩,可以通过以下方法实现。

1. 设置 Canvas 的宽高比

首先,Canvas 的宽度可以设置为屏幕宽度,保持其比例,这样它在屏幕上看起来是全屏的。与此同时,将 canvas 的实际像素大小设置为你希望的宽度(如 2000 像素),这样在保存图片时就可以保留高分辨率。

2. 通过 CSS 控制显示比例

通过 CSS 设置 Canvas 的 style 属性来控制它在屏幕上的显示比例,而 canvas 本身的实际尺寸(通过 width 和 height 属性设置)保持不变。

示例代码
<template>
  <view class="container">
    <canvas canvas-id="myCanvas" style="width: 100%; height: auto;"></canvas>
  </view>
</template>

<script>
export default {
  onReady() {
    this.initCanvas()
  },
  methods: {
    initCanvas() {
      // 获取屏幕宽度
      const systemInfo = uni.getSystemInfoSync()
      const screenWidth = systemInfo.windowWidth

      // 初始化 Canvas
      const ctx = uni.createCanvasContext('myCanvas')

      // 设置 Canvas 的实际大小(2000 像素宽)
      const canvasWidth = 2000
      const canvasHeight = 1000  // 根据比例设置高度

      // 设置 canvas 实际大小
      ctx.canvas.width = canvasWidth
      ctx.canvas.height = canvasHeight

      // 画一些内容作为示例
      ctx.setFillStyle('red')
      ctx.fillRect(0, 0, canvasWidth, canvasHeight)

      // 绘制完成
      ctx.draw()
    }
  }
}
</script>

<style>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
代码说明

Canvas 宽度设置:

在 initCanvas 方法中,获取了屏幕宽度,并将 Canvas 的 style 宽度设置为 100%,这样它在屏幕上会全屏显示。

实际像素设置:

使用 ctx.canvas.width 和 ctx.canvas.height 设置 Canvas 的实际像素尺寸。在这个例子中,我们将 Canvas 的实际宽度设置为 2000 像素。

绘制内容:

使用 CanvasContext 对象绘制内容,并在屏幕上渲染。绘制时,画布的实际尺寸是 2000x1000 像素,但它在屏幕上显示为全屏。

保存图片:

由于 Canvas 的实际尺寸是 2000 像素宽,所以即使在屏幕上按比例缩小显示,当你调用 canvasToTempFilePath 或 toDataURL 保存图片时,仍然会得到 2000 像素宽的高分辨率图片。3. 保存高分辨率图片
saveCanvas() {
  uni.canvasToTempFilePath({
    canvasId: 'myCanvas',
    fileType: 'jpg',
    success(res) {
      console.log('Saved image path:', res.tempFilePath);
    },
    fail(err) {
      console.error('Failed to save image:', err);
    }
  });
}

通过这种方法,你可以在 UniApp 中实现 Canvas 全屏显示,同时保持图片保存时的高分辨率。

网友回复

我知道答案,我要回答