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

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

  export default {
    data() {
      return {
24 25
        title: 'Context2D',
        canvas: null as UniCanvasElement | null,
26 27
        canvasContext: null as CanvasRenderingContext2D | null,
        canvasWidth: 0,
28 29
        canvasHeight: 0,
        dataBase64: '',
30 31 32
        // 仅测试
        testToBlobResult: false,
        testToDataURLResult: false
33 34 35 36 37 38 39 40
      }
    },
    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;
41 42 43 44 45 46

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

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

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

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
  .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 已提交
92
</style>