HTML5 canvas drawing whiteboard

Time:2020-7-15

Recently, I took over a small H5. The main function is probably to upload photos and canvas sketchpad.

It’s mainly about recording your own cooking skills like a fool.

1. Canvas’s Sketchpad hits cattle in the air! The higher the canvas is, the smaller the dislocation distance is, and the greater the downward distance is.

2. Picture upload! The content of whiteboard graffiti is transmitted to the back-end Engineer in the form of Base64. The picture uploaded from the picture is a path. The back-end requires a unified format, so the path needs to be changed to Base64.

3. It’s a limitation of Google. The front-end can send a request and the back-end can receive it, but the front-end can’t see the return value in the browser.

Make a note of the above questions. Record my solutions. It’s not the best, and it may be wrong. If you see that you can collide with your ideas or help you temporarily, that’s great. If not, I hope to get your help. Come on!

First of all, let’s talk about the general situation of the project. The project is an H5, which is native and the framework is Mui. Here’s the solution:

1. The solution to this problem is that if the width and height of the Sketchpad is equal to the width and height of the mobile phone screen, this problem will not occur. The reason for this problem is that you use the height on the page, and change the size of the canvas, thus changing the position. Don’t set the height of the CSS. If the requirements really need to be written, then use positioning, out of the document flow.

2. JS image to Base64

Method 1: blob and FileReader objects

Implementation principle:

  • Use XHR to request the picture and set the returned file type as blob object[ xhr.responseType = “blob”]
  • Receiving blobs using FileReader objects
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    < title > JS picture to Base64 mode
</head>

<body>
    <p id="container1"></p>
    <script>
        getBase64("https://z649319834.github.io/Learn_Example/video_track/webvtt.jpg")
        function getBase64(imgUrl) {
            window.URL = window.URL || window.webkitURL;
            var xhr = new XMLHttpRequest();
            xhr.open("get", imgUrl, true);
            //As long as you get this blob, the problem will be solved, so it's very important.
            xhr.responseType = "blob";
            xhr.onload = function () {
                if (this.status == 200) {
                    //At this point, we get a blob object
                    var blob = this.response;
                    console.log("blob", blob)
                    let oFileReader = new FileReader();
                    oFileReader.onloadend = function (e) {
                        let base64 = e.target.result;
                        console.log ("print it out, Base64)
                    };
                    oFileReader.readAsDataURL(blob);


                    //To display images on the page, you can delete them
                    var img = document.createElement("img");
                    img.onload = function (e) {
                        window.URL.revokeObjectURL ( img.src ); // clear and release
                    };
                    let src = window.URL.createObjectURL(blob);

                    img.src = src
                    document.getElementById("container1").appendChild(img);
                }
            }
            xhr.send();
        }

    </script>
</body>

</html>

Method 2: canvas.toDataURL () method

Implementation principle:

  • use canvas.toDataURL () method
  • Need to solve the problem of image cross domain image.crossOrigin = ”;
  • The $. Deferred () method of jQuery library is used
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    < title > JS picture to Base64 mode
</head>

<body>
<p id="container2"></p>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
        let imgSrc = "https://z649319834.github.io/Learn_Example/video_track/webvtt.jpg";

        //When width and height are called, the specific pixel value is passed in to control the size. If not, the default image size is used
        function getBase64Image(img, width, height) {
            var canvas = document.createElement("canvas");
            canvas.width = width ? width : img.width;
            canvas.height = height ? height : img.height;

            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            var dataURL = canvas.toDataURL();
            return dataURL;
        }
        function getCanvasBase64(img) {
            var image = new Image();
            image.crossOrigin = '';
            image.src = img;
            var deferred = $.Deferred();
            if (img) {
                image.onload = function () {
                    deferred.resolve (getbase64image (image)); // transfer Base64 to done for upload processing
                    document.getElementById("container2").appendChild(image);
                }
                return  deferred.promise (); // for the problem, let onload complete before returning sessionstorage ['imgtest ']
            }
        }
        getCanvasBase64(imgSrc)
            .then(function (base64) {
                console.log (see the results, Base64);
            }, function (err) {
                console.log(err);
            });
    </script>
</body>

</html>

3. The front-end calls the interface and returns 200, but the network response of the console is empty and no information is displayed.

terms of settlement:

1. In JS debugger, you can see whether the background has returned data.

2. Direct console.log (), print the return value directly, check the returned data format, and facilitate the front-end data processing.

Because the back-end returns a lot of data and the data format is complex, it may be that Chrome’s response controls the length or size of the data, so it is not displayed.

In addition, a console error prompt, uncaught sy, was found ntaxError:Invalid shorthand property initializer

The reason is that a colon is written as “=”

Solution: change the equal sign to a colon;

At the end

This article on the HTML5 canvas drawing whiteboard pit of the article introduced here, more related HTML5 canvas whiteboard content, please search the previous articles of developpaer or continue to browse the related articles below, I hope you can support developeppaer more in the future!

Recommended Today

Go carbon version 1.2.0 has been released to improve and optimize the multi scenario support for orm

Carbon is a lightweight, semantic and developer friendly golang time processing library, which supports chain call, lunar calendar, Gorm, xorm and other mainstream orm If you think it’s good, please give it to a star github:github.com/golang-module/carbon gitee:gitee.com/go-package/carbon Installation and use //Using GitHub Library go get -u github.com/golang-module/carbon import ( “github.com/golang-module/carbon”) //Using gitee Library go get […]