通过js保存图片到本地中遇到的跨域问题

JavaScript014

通过js保存图片到本地中遇到的跨域问题,第1张

<html>

<meta http-equiv="X-UA-Compatible" content="chrome=1">

<head>

<script>

     window.onload = function() {

     draw()

     var saveButton = document.getElementById("saveImageBtn")

     bindButtonEvent(saveButton, "click", saveImageInfo)

     var dlButton = document.getElementById("downloadImageBtn")

     bindButtonEvent(dlButton, "click", saveAsLocalImage)

     }

            function draw(){

                var canvas = document.getElementById("thecanvas")

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

                ctx.fillStyle = "rgba(125, 46, 138, 0.5)"

                ctx.fillRect(25,25,100,100) 

                ctx.fillStyle = "rgba( 0, 146, 38, 0.5)"

                ctx.fillRect(58, 74, 125, 100)

                ctx.fillStyle = "rgba( 0, 0, 0, 1)" // black color

                ctx.fillText("Gloomyfish - Demo", 50, 50)

            }

            

            function bindButtonEvent(element, type, handler)

            {

                if(element.addEventListener) {

                   element.addEventListener(type, handler, false)

                } else {

                   element.attachEvent('on'+type, handler)

                }

}

            

            function saveImageInfo () 

            {

             var mycanvas = document.getElementById("thecanvas")

             var image    = mycanvas.toDataURL("image/png")

             var w=window.open('about:blank','image from canvas')

             w.document.write("<img src='"+image+"' alt='from canvas'/>")

            }

            function saveAsLocalImage () {

             var myCanvas = document.getElementById("thecanvas")

         // here is the most important part because if you dont replace you will get a DOM 18 exception.

         // var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-streamContent-Disposition: attachmentfilename=foobar.png")

         var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream") 

         window.location.href=image // it will save locally

         }

        </script>

</head>

<body bgcolor="#E6E6FA">

<div>

<canvas width=200 height=200 id="thecanvas"></canvas>

<button id="saveImageBtn">Save Image</button>

<button id="downloadImageBtn">Download Image</button>

</div>

</body>

</html>

好像这个可以 不错 你试一试吧 把下载下来的文件 重命名 为 图片格式 就可以预览啦

项目中遇到一个问题,同一个图片在 dom 节点中使用了 <img>标签来加载,同时由于项目使用了 ThreeJS 3D 渲染引擎,在加载纹理时使用了 TextureLoader 来加载了同一张图片,而由于图片是在阿里云服务器上的,所以最后报出了跨域问题。 https://www.jianshu.com/p/8fa0fb53c183

将图片转换为Base64

获取图片Base64编码

方式一:Blob和FileReader 对象

实现原理:

使用xhr请求图片,并设置返回的文件类型为Blob对象[xhr.responseType = "blob"]

使用FileReader 对象接收blob

方式二:canvas.toDataURL()方法

实现原理:

使用canvas.toDataURL()方法

需要解决图片跨域问题 image.crossOrigin = ''

使用了Jquery库的$.Deferred()方法