利用PWA通过社交媒体分享图片
P粉300541798
P粉300541798 2024-01-28 22:02:28
0
2
406

在我的 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粉300541798
P粉300541798

全部回复(2)
P粉883973481

我的应用程序中的 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);            
    }
  });
};
P粉916553895

告诉我这个网址是否适合您:https://nuxt-share-social- media.netlify.app
如果是这样,您可以在此处找到 Github 存储库: https://github.com/ Kissu/so-share-image-bounty

代码是



sssccc

灵感来自@denvercoder9!

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!