svgToblob.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* 针对系统中众多svg的图表/沙盘想要复制粘到微信中 */
  2. import bus from '@/api/bus.js';
  3. export const copyBlob = (url,callback=null,ratio=1,urlType='svg') => {
  4. const copyImg = new Image()
  5. copyImg.crossOrigin = 'anonymous';
  6. copyImg.src = urlType==='svg'?svgToBase64(url):url;
  7. copyImg.onload = ()=> {
  8. const canvas = document.createElement('canvas');
  9. canvas.width = copyImg.width * ratio;
  10. canvas.height = copyImg.height * ratio;
  11. const ctx = canvas.getContext("2d");
  12. ctx.drawImage(copyImg,0,0,canvas.width,canvas.height)
  13. ctx.scale(ratio,ratio)
  14. callback && callback();
  15. if(window.ClipboardItem) {
  16. canvas.toBlob(async(blob) => {
  17. console.log('toblob')
  18. console.log(blob)
  19. const data = [new ClipboardItem({ [blob.type]: blob })];
  20. await navigator.clipboard.write(data).then(
  21. () => {
  22. bus.$message.success('复制成功!')
  23. },
  24. () => {
  25. bus.$message.warning('浏览器暂不支持')
  26. }
  27. );
  28. })
  29. }else {
  30. bus.$message.warning('当前协议暂不支持,仅支持https协议')
  31. }
  32. }
  33. }
  34. /* 转base64 */
  35. export const svgToBase64 = (svg) => {
  36. const base64img = `data:image/svg+xml;base64,${window.btoa(
  37. unescape(encodeURI(svg))
  38. )}`;
  39. return base64img;
  40. }
  41. /* 不受粘贴板对象影响的粘贴 */
  42. export function copyFit(value) {
  43. if(navigator.clipboard) {
  44. navigator.clipboard.writeText(value)
  45. }else {
  46. setTimeout(() => {
  47. const input = document.createElement('input')
  48. input.setAttribute('readonly','readonly')
  49. input.setAttribute('id',new Date().getTime())
  50. input.value = value
  51. document.body.appendChild(input)
  52. input.select();
  53. document.execCommand('copy');
  54. document.body.removeChild(input);
  55. })
  56. }
  57. }