Canvas implements sample code to save images locally

Time:2019-6-5

I. Introduction

Requirement: Save HTML5 content as a picture
Thought: Generate Base64 pictures by Canvas drawing, and save them locally by long press
Question: Canvas prohibits cross-domain, Android Wechat Length from compressing pictures that cannot be saved by Base64 or pulled by servers

II. Specific issues

Question 1: Canvas is forbidden to cross domains. If the image comes from other domains, calling toDataURL () throws an error.

Solution: <img> Label can solve cross-domain problem by introducing crossorigin attribute, that is, crossOrigin= “Anonymous” or crossOrigin=”*” Note that setting’Anonymous’in hand Q environment does not support, it needs to be set to’*’, if using crossorigin= “anonymous”, it is equivalent to anonymous CORS.

Question 2: The < img > tag with “cross Origin” cannot pull down cross-domain images and trigger img. onload.

Solution: Background forwarding or nigix proxy, setting Access-Control-Allow-Origin: “wx.qlogo.cn”, allowing static resource server image cross-domain settings to solve the problem of obtaining cross-domain images. (The picture here is the user’s avatar domain name wx.qlogo.cn. There is a cross-domain problem)

Question 3: Android Mobile Wechat H5 Long Press Can’t Save Base64 Pictures

Solution: upload the base64 picture drawn by canvas to the server, and then get the PNG (jpg) picture from the server. This method is more troublesome, and we need to find ways to improve it later.

Problem 4: The image uploaded to the server is severely compressed

Solution: Uploaded images will have several resources on the server, with varying degrees of compression. Pictures with clearer pixels can be obtained from the directory’http://img10.360buyimg.com/promotepic/’.

Question 5: Drawn two-dimensional code links (//wqs.jd.com/xxx) long press cannot directly enter the page

Solution: Specify that the links to the two-dimensional codes to be drawn must be http: otherwise the two-dimensional codes will be recognized as text

// Canvas draws part of the code:

var picurl = "http://wx.qlogo.cn/mmopen/OicsrgN57fqDxImI3icnMeSXRfVUQRueHcxRRuWG0O1Ea1bNyBPKKKLeq5FiaXFWOdsltVe1R1PtJ2EtsDHYDjHgQ/0";
   var img = new Image,
    canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d"),
      // Background nigix proxy see question 2
      src = picurl.replace("http://wx.qlogo.cn","//wq.jd.com");
      // Solve the problem that canvas cross-domain toDataURL cannot be read. See Question 1
      img.crossOrigin = "Anonymous";
      // Preloading of Picture Resources
       img.onload = function() {
             canvas.width = img.width;
            canvas.height = img.height;
             ctx.drawImage( img, 0, 0 );
            // Base64 Pictures to be Painted
             localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") );
      }
       img.src = src;

Upload the picture part code:

// Upload pictures. See Question 3
$.ajax({
    type: 'POST',
    url:  loadJs.addToken('http://wq.jd.com/activetmp/promotepic/promoteaddpic', "j132"),
    data: {
        filename: new Date().getTime()+''+Math.floor(Math.random()*10000) + '.jpg',
        content: base64pic,
        active: "shotpic20160901"
    },
    dataType: 'json',
    xhrFields: { withCredentials: true },
    success: function(data) {
                           if (picdata.id == 1 && picdata.msg) {
                                    // Picture paths with prefix paths are the clearest pictures. See Question 4
                                    var imgPre = 'http://img10.360buyimg.com/promotepic/';
                                    // Complete Address Links for Image Address Stitching
                                    var photo = imgPre + picdata.msg;
                                    $("#cardImg")[0].onload = function() {
                                             // to do business logic
                                    };
                                    $("#cardImg").attr("src",photo);
                           }
    },
    error:function(data){
    }
});

The above is the whole content of this article. I hope it will be helpful to everyone’s study, and I hope you will support developpaer more.