首頁  >  問答  >  主體

利用PWA透過社群媒體分享圖片

在我的 Nuxt PWA 中,我有一個函數可以使用這個套件將 HTML 轉換為 Canvas。生成的影像採用 64 進位。現在我希望能夠透過以下方式分享該圖像:Whatsapp、Facebook、電子郵件、Instagram 等。我找到了幾個軟體包,但它們似乎都不支援僅共享文件 URL 和文字。

這是我的分享功能:

shareTicket(index) {
  html2canvas(this.$refs['ticket-' + index][0], {
    backgroundColor: '#efefef',
    useCORS: true, // if the contents of screenshots, there are images, there may be a case of cross-domain, add this parameter, the cross-domain file to solve the problem
  }).then((canvas) => {
    let url = canvas.toDataURL('image/png') // finally produced image url

    if (navigator.share) {
      navigator.share({
        title: 'Title to be shared',
        text: 'Text to be shared',
        url: this.url,
      })
    }
  })

當我取出 if (navigator.share) 條件時,我的控制台中出現錯誤,指出 navigator.share 不是函數。我在某處讀到它僅適用於 HTTPS,因此我上傳到我的臨時伺服器並嘗試,但仍然遇到相同的錯誤。

需要明確的是,我希望能夠共享生成的圖像本身,而不是 URL。

P粉300541798P粉300541798264 天前411

全部回覆(2)我來回復

  • P粉883973481

    P粉8839734812024-01-29 20:56:31

    我的應用程式中的 share() 函數中有以下程式碼的變體,如果在客戶端上執行,它可以正常運作。

    const share = async() => {
      if (!('share' in navigator)) {
        return;
      }
      // `element` is the HTML element you want to share.
      // `backgroundColor` is the desired background color.
      const canvas = await html2canvas(element, {
        backgroundColor,
      });
      canvas.toBlob(async (blob) => {
        // Even if you want to share just one file you need to 
        // send them as an array of files.
        const files = [new File([blob], 'image.png', { type: blob.type })];
        const shareData = {
          text: 'Some text',
          title: 'Some title',
          files,
        };
        if (navigator.canShare(shareData)) {
          try {
            await navigator.share(shareData);
          } catch (err) {
            if (err.name !== 'AbortError') {
              console.error(err.name, err.message);      
            }
          }
        } else {
          console.warn('Sharing not supported', shareData);            
        }
      });
    };
    

    回覆
    0
  • P粉916553895

    P粉9165538952024-01-29 13:38:48

    告訴我這個網址適合您:https://nuxt-share-social- media.netlify.app
    # 如果是這樣,您可以在此處找到 Github 儲存庫: https://github.com/ Kissu/so-share-image-bounty

    程式碼是

    
    
    sssccc
    

    靈感來自@denvercoder9!

    回覆
    0
  • 取消回覆