Canvas implements sample code to save images locally


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: “”, 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 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’’.

Question 5: Drawn two-dimensional code links (// 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 = "";
   var img = new Image,
    canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d"),
      // Background nigix proxy see question 2
      src = picurl.replace("","//");
      // 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
    type: 'POST',
    url:  loadJs.addToken('', "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 ( == 1 && picdata.msg) {
                                    // Picture paths with prefix paths are the clearest pictures. See Question 4
                                    var imgPre = '';
                                    // Complete Address Links for Image Address Stitching
                                    var photo = imgPre + picdata.msg;
                                    $("#cardImg")[0].onload = function() {
                                             // to do business logic

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.