canvas.uvue 2.4 KB
Newer Older
X
xty 已提交
1
<template>
2 3
  <view class="page" id="page-canvas">
    <canvas id="canvas" class="canvas-element"></canvas>
H
hdx 已提交
4 5
    <scroll-view class="scroll-view">
      <!-- #ifdef WEB -->
6
      <button class="canvas-drawing-button" @click="canvasToBlob">canvasToBlob</button>
H
hdx 已提交
7
      <!-- #endif -->
8 9
      <button class="canvas-drawing-button" @click="canvasToDataURL">canvasToDataURL</button>
      <text>{{dataBase64}}</text>
10 11 12 13 14 15 16
    </scroll-view>
  </view>
</template>

<script>
  function hidpi(canvas : UniCanvasElement) {
    const context = canvas.getContext("2d")!;
17
    const dpr = uni.getDeviceInfo().devicePixelRatio ?? 1;
18 19 20 21 22 23 24 25
    canvas.width = canvas.offsetWidth * dpr;
    canvas.height = canvas.offsetHeight * dpr;
    context.scale(dpr, dpr);
  }

  export default {
    data() {
      return {
26 27
        title: 'Context2D',
        canvas: null as UniCanvasElement | null,
28 29
        canvasContext: null as CanvasRenderingContext2D | null,
        canvasWidth: 0,
30 31
        canvasHeight: 0,
        dataBase64: '',
32 33 34
        // 仅测试
        testToBlobResult: false,
        testToDataURLResult: false
35 36 37 38 39 40 41 42
      }
    },
    onReady() {
      let canvas = uni.getElementById("canvas") as UniCanvasElement
      this.canvasContext = canvas.getContext("2d");
      hidpi(canvas);
      this.canvasWidth = this.canvasContext!.canvas.width;
      this.canvasHeight = this.canvasContext!.canvas.height;
43 44 45 46 47 48

      // #ifdef WEB
      canvas.toBlob((blob : Blob) => {
        this.testToBlobResult = (blob.size > 0 && blob.type == 'image/jpeg')
      }, 'image/jpeg', 0.95)
      // #endif
49 50 51
      this.testToDataURLResult = canvas.toDataURL().startsWith('data:image/png;base64')

      this.canvas = canvas;
52
    },
53
    methods: {
H
hdx 已提交
54
      // #ifdef WEB
55 56 57 58 59
      canvasToBlob() {
        this.canvas!.toBlob((blob : Blob) => {
          this.testToBlobResult = (blob.size > 0 && blob.type == 'image/jpeg')
        }, 'image/jpeg', 0.95)
      },
H
hdx 已提交
60
      // #endif
61 62
      canvasToDataURL() {
        this.dataBase64 = this.canvas!.toDataURL()
63 64 65
      }
    }
  }
X
xty 已提交
66 67 68
</script>

<style>
69 70 71 72 73
  .page {
    flex: 1;
    height: 100%;
    overflow: hidden;
  }
X
xty 已提交
74

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
  .scroll-view {
    flex: 1;
  }

  .canvas-element {
    width: 100%;
    height: 250px;
    background-color: #ffffff;
  }

  .grid-view {
    padding: 10px;
    flex-direction: row;
    flex-wrap: wrap;
  }

  .btn-to-image {
    margin: 10px;
  }
X
xty 已提交
94
</style>