图片转静态html,将在线图片转换成base64踩坑记录及静态资源跨域及缓存的处理...

1、在线图片资源跨域的问题

解决方法:将“跨域图片资源”转换成base64后,用base64渲染img标签,这样完美解决问题;

如何将“跨域图片”转换成base64呢?原理很简单,将img绘制成canvas,再将canvas转换成base64的img流;

因为图片是跨域的,所以我们在转换过程中需要加一段代码:image.crossOrigin = "*";,用来处理跨域;

let image = newImage()

image.src= this.networkImgimage.crossOrigin= "*"

发现偶尔还是会报错:Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

2、图片url缓存

在这里能找到答案:https://stackoverflow.com/questions/46609800/canvas-crossorigin-anonymous-cors-chrile-mac-osx

If your images come from a different domain, and you want to be able to export the canvas content after you did draw these images, then you have no choice than loading them with the crossOrigin attribute.

If you are really facing the linked bug, according to it, the proper fix is to always send the CORS headers from your server response, whether or not the request is made with the Origin header.

And a fast workaround is to avoid the cache, by appending a random query string in the image's src (img.src = url + '?v=' + Math.random();).

需要加个随机数防止缓存即可

let image = newImage()

image.src= this.networkImg + '?v=' +Math.random()

image.crossOrigin= "*"

我代码里的解决

insertImg () {

let _this= thislet image= newImage()

image.src= this.networkImg + '?v=' +Math.random()

image.crossOrigin= "*"image.οnlοad=function(){

let base64=_this.getBase64Image(image)

_this.talkInfo.imageUrls.push(base64)

_this.networkImg= ''}

},

getBase64Image (img) {

let canvas= document.createElement("canvas")

canvas.width=img.width

canvas.height=img.height

let ctx= canvas.getContext("2d")

ctx.drawImage(img,0, 0, img.width, img.height)

let dataURL= canvas.toDataURL("image/png")returndataURL

},

思路:

1、image的onload下载图片资源

2、利用canvas转换base64

3、避免跨域及缓存的坑

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值