教你在canvas上繪制Base64格式的圖片


現象描述

當前canvas組件只支持繪制本地圖片和網絡圖片,暫不支持繪制Base64字符串表示的圖片格式,下面介紹如何采取規避措施實現。

問題分析

當前image組件支持Base64字符串表示的圖片格式,如下所示:

因此可以考慮通過image組件來表示Base64字符串表示的圖片,然后用canvas組件繪制image元素來間接實現繪制Base64字符串表示的圖片格式。

解決方法

代碼如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
< template >
   < div  class = "container" >
     < image  id = "Image"  src={{imageSrc}}  show = "false" ></ image >
     < canvas  id = "Canvas"  style = " margin-top:20px;width: 100%; height:50%;" ></ canvas >
     < input  class = "buttons"  type = "button"  onclick = "drawImageAll"  value = "saveImageAndShowCanvas" ></ input >
   </ div >
</ template >
  
< style >
   .container {
     flex-direction: column;
     justify-content: center;
     align-content: center;
     align-items: center;
   }
  
   .title {
     font-size: 100px;
   }
  
   .text {
     font-size: 50px;
     color: #0000ff;
     border: 1px;
   }
</ style >
  
< script >
   module.exports = {
     data: {
       imageSrc: "填寫需要繪制的圖片對應的base64字符串" //格式如:"data:image/png;base64,iVBORw0KGgoAAAA……"
     },
     onInit() {
       this.$page.setTitleBar({text: 'Canvas'})
     },
     drawImageAll(){
       var test = this.$element("Canvas");
       var ctx = test.getContext("2d");
       var img = this.$element('Image');
       ctx.drawImage(img, 0,0);
   }
   }
</ script >

 

原文鏈接:https://developer.huawei.com/consumer/cn/forum/topic/0201429219344610026?fid=18

原作者:Mayism


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM