Recently, I made a requirement to provide several cut diagrams. The front end splices the slice map and the text information returned by the background together to draw a picture. Then it will download, or upload. It’s actually pretty easy to do. Here’s the general process.
Front-end drawing can only use canvas.
1. Canvas API is mainly used as follows:
let cvs = document.createElement('canvas');
let ctx = cvs.getContext('2d');
// Set the fill color, also can set the font color
ctx.fillStyle = bgcColor;
// Set the text message. Font, size, font-weight, etc.
ctx.font = 'bold 20px 宋体';
// Set the text alignment
ctx.textAlign = 'center'; // left || right || center || start || end; There are five values in total, usually left and center.
// Set the text baseline alignment similar to vertical-align of the CSS
ctx.textBaseLine = 'middle'; // top || hanging || middle || alphabetic || ideographic || bottom
// Draw text text: text content. X: the x coordinate of the text. Y: the y coordinate of the text. MaxWidth: The maximum width for drawing text.
ctx.fillText(text, x, y, maxWidth);
This method returns an object with a width property.
ctx.measureText(text)
// Draw a rectangle
ctx.fillRect(0.0, width, height);
// Draw the image img: the target image. X: the x coordinate. Y: the y coordinate. Width: draw width. Height: The height of the drawing.
ctx.drawImg(img, x, y, width, height);
/ / draw circle
ctx.arc()
Copy the code
Details of the canvas reference https://www.w3cplus.com/blog/tags/616.html
2. After drawing with Canvas. Provide export and download
Canvas has two apis. You can convert the drawn image into a downloadable file.
The canvas.todataURL () method returns a dataURL containing the image presentation. You can use the type parameter to set the type. The default value is PNG. The resolution of the image is96dpi; * If the height or width of the canvas is0The string "data:," * is returned if the type passed is not"image/png", but the returned value is"data:image/png"Beginning, then the type is not supported. * chrome support"image/webp"typeCopy the code
grammar
canvas.toDataURL(type, encoderOptions);
Copy the code
parameter
Type: image format. The default for the image/PNG; EncoderOptions: in the specified format'image/jpeg','image/webp'Can be set from0 - 1To change the quality of the picture. If the value exceeds the range, the value is set to0.92. Other parameters are ignoredCopy the code
The return value
Return a DOMString (base64) that contains the dataURL;Copy the code
How to download
// Download method.
/** *@param imgSrc file link can be either a dataURL or a BLOb object. *@param imgName Name of the downloaded file. * /
function downloadImg (imgSrc, imgName) {
let elem = document.createElement('a');
elem.setAttribute('href', imgSrc);
elem.setAttribute('download', imgName);
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
Copy the code
After looking at the above methods, this requirement is relatively simple
let cvs = document.createElement('canvas');
let ctx = cvs.getContext('2d'); .// The image is drawn
let imgSrc = ctx.toDataURL('image/jpeg'.0.9);
let imgName = 'Test picture.jpg';
downloadImg(imgSrc, imgName); // The browser will download automatically
Copy the code
At first, I used this method, but when I drew a large image, the browser would tell me that the download had failed. I checked the data and found that there was a size limit for downloading using dataURL. Later, I checked the data again and found that I could download it using BLOB.
About blob details please refer to: https://developer.mozilla.org/zh-CN/docs/Web/API/Blob
How does a Canvas turn into a blob
grammar
canvas.toBlob(callback, type, encoderOption);
Copy the code
parameter
Callback: Since converting canvas to blob is an asynchronous operation, it requires a callback function that takes the blob object as an argument. Type: specifies the image format. The default value is:'image/png'; EncoderOption: in the specified format'image/jpeg','image/webp'Can be set from0 - 1To change the quality of the picture. If the value exceeds the range, the value is set to0.92. Other parameters are ignoredCopy the code
This method returns no value.
Ok, now how to download using blob
let cvs = document.createElement('canvas');
let ctx = cvs.getContext('2d'); .// The image is drawn
ctx.toBlob(function (blob) {
let imgSrc = window.URL.createObjectURL(blob);
let imgName = 'Test picture.jpg';
downloadImg(imgSrc, imgName);
window.URL.revokeObjectURL(imgSrc);
}, 'image/jpeg'.0.9)
Copy the code
There are two methods that I haven’t seen before, so I’ll write them down today. \
Url.createobjecturl () See the description of this method on MDN, which is an experimental feature that is still under development in some browsers. The documentation for this standard may be revised, so the syntax and behavior of this feature may change in future versions of browsers. These things, I will talk about later, now is not so much. All blame products ^_^).
The url.createObjecturl () static method creates a DOMString with a URL representing the object given in the argument. The lifecycle of this URL and the Document binding in the window that created it. This new URL object represents the specified File object or Blob object. grammar
objectURL = URL.createObjectURL(blob); // Window can be omitted
Copy the code
Parameter is used to create a File or Blob object for the URL. Every time the url.createObjecturl (blob) method is called, a new URL object is created, even though it has already been created with the same parameters. Therefore, when the URL object is no longer needed, it must be released by calling url.revokeobjecturl (). Browsers release documents when they exit, but for best performance and memory, you should actively release them when it is safe to do so.
RevokeObjectURL () Static method is used to release a URL object that was previously generated by calling url.createObjecturl (blob).
grammar
window.URL.revokeObjectURL(objectUrl)
Copy the code
parameter
ObjectUrl: URL object generated by the url.createObjecturl (blob) method;Copy the code
Today I’m going to write down how to download it. Record how to upload pictures tomorrow