start of literary work
Recently I've been working on a feature to take screenshots of images.
Because of the tight work schedule.
Was using a screenshot plugin.
Weekend two days have nothing to do, to write a simple version of the screenshot function.
Because the writing is relatively simple, if the writing is not good, please big brother light a little spray!
Read the image and get the width and height of the image ideas
First of all to read a file we use input in which the type is file.
We need to restrict the object to be read, it must be of type image.
This can be achieved by using this attribute: accept="image/*"
But this attribute is unreliable, it is better to use regularization.
To get the width and height of the image, we need to create a FileReader object.
Read the contents of the file asynchronously, using (file)
and encode it as a Data URL (data URL)
When the file is read, an event is fired.
At this point we have to create an image object.
Wait for the image to finish reading, and then return the width and height of the image via , .
Here's a simple implementation
Read the image and get the width of the image
<div>
<input type="file" accept="image/*" />
</div>
<script>
// Get the file node
let fileNode = ("file")
// Register an event for the file node
("change", readFile)
// Read the file and return the width and height.
function readFile(e){
function readFile(e){ let file = [0]
getImageWH(file, function(width, height) {
('Width:', width, 'Height:', height); }); let file = [0] getImageWH(file, function(width, height) {
});
}
// Return the file (width and height of the image)
function getImageWH(file, callback) {
// Create a FileReader instance
const reader = new FileReader(); // Create a FileReader instance.
// Triggered when file reading is complete
= function(e) {
// e This object contains the properties associated with this image.
('e this object', e)
// Create a new Image object
const img = new Image();
// Set the src of the Image to the contents of the read file.
= ;
// Triggered when the image is loaded
= function() {
// Call the callback function, passing in the width and height of the image.
callback(, );; // Call the callback function and pass in the width and height of the image.
}; }
}; // Start reading the contents of the file as a DataURL.
// Start reading the contents of the file as a DataURL.
The // method is executed by calling the following
(file); }
}
</script>
Assigns the width and height of the image to the canvas.
We get the width and height of the image and assign it to the canvas.
And just display the canvas.
This step is relatively simple
<style>
.canvas-box{
border: 1px solid red;
display: none;
}
</style>
<canvas class="canvas-box"></canvas>
// gaincanvasnodal
let canvasNode = ("canvas-node")
// Read file
function readFile(e){
let file = [0]
getImageWH(file, function(width, height) {
// Pass the width and height to thecanvasSetWHfunction (math.),Show on page
canvasSetWH(canvasNode,width, height)
});
}
function canvasSetWH(canvasNode,width, height){
= width
= height
= "block"
}
Displaying image content in canvas
To draw the image, we need to use the drawImage API.
This API has three types of passes
Type 1: drawImage(image, x, y)
image: the source of the image to be drawn
x, y: the starting coordinates of the image on the canvas (x,y), the image will be drawn in its original size
Type 2: drawImage(image, x, y, width, height)
image: the source of the image to be drawn
x, y: starting coordinates of the image on the canvas (x,y)
width, height(optional): width and height of the image to be drawn to the canvas
Type 3: drawImage(image, sx, sy, swidth, sheight, dx, dy, dwidth, dheight)
image: the source of the image to be drawn
sx, sy: starting coordinates of the rectangular area in the image source
swidth, sheight: width and height of the rectangular area in the image source, i.e. the part of the image to be drawn
dx, dy: the starting coordinates of the canvas to draw on.
dwidth, dheight: width and height of the rectangular area drawn to the canvas, allowing scaling of the drawn image.
That is to say: we can use the first and second methods for drawing here.
The image source is returned in the method getImageWH.
// Return the file (width and height of the image and the image source)
function getImageWH(file, callback) {
// .... Other code .....
// Triggered when file reading is complete
= function(e) {
// .... Other code .....
// Triggered when an image is loaded
= function() {
// Call the callback function to return the image source, width, and height of the image
callback(img,, );
}; }
}; }
// Start reading the contents of the file as a DataURL.
// The execution of the method requires the following call
(file); }
}
// Get the canvas node
let canvasNode = ("canvas-node")
// Create the context
let ctx = ("2d")
function readFile(e){
let file = [0]
getImageWH(file, function(img, width, height) {
// Pass the width and height to the canvasSetWH function to display on the page
canvasSetWH(canvasNode, width, height)
// Draw the image
(img, 0, 0,width, height );
});
}
Drawing Masks
Drawing the mask is a relatively simple step.
We just need to draw a mask on the image with the same size as the image.
We can use fillStyle to fill the color and fillRect to draw a rectangle.
Here is a simple implementation
// Call the method that draws the mask (call this function when you're done drawing the image)
drawMask(0,0,width, height); // Call the method that draws the mask (call this function after the image is drawn).
// Draw the mask
function drawMask(x, y, width, height, opactity) {
= "rgba(0,0,0,0,0.5)"; // draw the mask.
(x, y, width, height);
}
Drawing the screenshot area
We need to bind a mouse press event to the canvas.
When the mouse is pressed, the coordinates of the current mouse are recorded (x,y).
We also need to register a move event and a lift event when the mouse is pressed.
Calculate the position of the mask (rectEndX,rectEndY) when the mouse is moved.
Then calculate the position of the screenshot area
Finally, we need to remove the move event and lift event when the mouse is lifted.
Here is a simple implementation
.... Other codes .....
// Image source
let img = new Image();
// Register an event to get the offset of the mouse when it is pressed.
("mousedown", mousedownInCanvasHandler)
let currentPoint = {}
// Mouse down
function mousedownInCanvasHandler(e){
currentPoint= { x: , y: }
// When the mouse is pressed we need to register the move and lift events
('mousemove', mousemoveInCanvasHandler)
('mouseup', mouseupInCanvasHandler)
}
// Draw the rectangle
function mousemoveInCanvasHandler(e){
let rectEndX =
let rectEndY =
// Get the width and height of the rectangle
let rectWidth = rectEndX -
let rectHeight = rectEndY -
let {width, height} = canvasNode
(0, 0, width, height)
// Draw the mask
drawMask(0,0,width, height); drawScreenShot(width, height); // Draw the mask.
drawScreenShot(width, height, rectWidth, rectHeight)
}
// Draw the screen shot
function drawScreenShot( canvasWidth, canvasHeight,rectWidth,rectHeight){
// Draw a rectangle outside of the original shape.
= "destination-out".
= '#000'
(, ,rectWidth,rectHeight)
= 'destination-over'
// Draw a rectangle for the screenshot area
(img, 0, 0,canvasWidth, canvasHeight,0,0,canvasWidth, canvasHeight );
}
// Remove the move event and the lift event when the mouse is raised
function mouseupInCanvasHandler(e){
('mousemove', mousemoveInCanvasHandler)
('mouseup', mouseupInCanvasHandler)
}
.... Other code .....
Show the area of the screenshot
All we need to do is after the screenshot is complete (on mouse up)
get the information about the screenshot area ()
and then write the information about the screenshot area to a new canvas.
Empty the canvas before drawing
<style>
.canvas-box,.canvas2-box{
display: none;
}
</style>
<body>
<! -- file reading --> <!
<div>
<input type="file" accept="image/*" />
/> </div>
<canvas class="canvas-box"> </canvas>
<! -- The image of the screenshot area is displayed on this new canvas below -->
<div class="canvas2-box">
<canvas > </canvas>
</div>.
</body> </div> </div
// Save the data for the screenshot area
screenshotData= [, , rectWidth, rectHeight]
// Remove the move event and the lift event when the mouse is raised
function mouseupInCanvasHandler(e){
('mousemove', mousemoveInCanvasHandler)
('mouseup', mouseupInCanvasHandler)
drawScreenShotImg(screenshotData)
}
// Draw a screenshot of the area on the other canvas and display it
function drawScreenShotImg(screenshotData){
// screenshotData is the start and end coordinates of the screenshot.
let drawData = (... .screenshotData)
canvasSetWH(canvas2Box,screenshotData[2],screenshotData[3])
// Empty the canvas first, pay attention to the size of the empty, otherwise it will cause an overlay (not clean)
(0,0, , )
// Draw the screenshot area onto canvas2
(drawData,0,0)
}
Download the portion of the screenshot area
To download a canvas, you need to use the
Syntax:(picType, encoderOptions)
Parameters.
picType: the format of the image. Default is image/png.
encoderOptions: select the quality of the image from 0 to 1.
If the value is out of the range, the default value of 0.92 will be used, other parameters will be ignored.
Getting the type of the image can be done with ()
let file = [0]
// Get the type of the image, which you'll need to download later.
fileType =
<button >down</button>
// Register the download event
('click',()=>{
let {width, height} = canvas2
// The first parameter of the toDataURL: the image format, which defaults to image/png, // the first parameter of the toDataURL: the image format, which defaults to image/png.
// The 2nd parameter: the quality of the image can be selected from the interval 0 to 1.
let imgURL = ( fileType, 1); // let link = ('a')
let link = ('a'); // The second parameter: the quality of the image can be selected from 0 to 1.
= "Screenshot image".
= imgURL.
(link);
(); let
(link);
})
Screenshot function all code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"> <meta name="viewer"> <header>
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>
<title> canvas realize screenshot function</title>
<style>.
.canvas-box,.canvas2-box{
display: none;
}
</style>
</head>
<body>
<! -- file reading --> <!
<div>
<input type="file" accept="image/*" />
/> </div>
<canvas class="canvas-box"></canvas> </canvas>
<button >down</button>
<div class="canvas2-box"> </canvas>
<canvas > </canvas>
</div>.
</body>.
<script>
// Get the canvas node
let canvasNode = ("canvas-node")
// Create the context
let ctx = ("2d")
let downBtn = ("downBtn")
let canvas2Box = (".canvas2-box")
let canvas2 = ("canvas2")
let ctx2 = ("2d")
// Get the file node
let fileNode = ("file")
// Register the event for the file node
("change", readFile)
// Image source
let img = new Image(); // The data for the screenshot area.
// Data for the screenshot area
let screenshotData = []
let fileType = "" // The type of the file, which will be needed when downloading.
// Register an event to get the offset when the mouse is pressed.
("mousedown", mousedownInCanvasHandler)
let currentPoint = {}
// Register the download event
('click',()=>{
let {width, height} = canvas2
// format: indicates the type of the image "image/png"
// First parameter of toDataURL: the format of the image, defaults to image/png, // the first parameter of toDataURL: the format of the image, defaults to image/png.
// The second parameter: the quality of the image can be selected from 0 to 1. If the value is out of the range, the default value of 0.92 will be used, and the other parameters will be ignored.
let imgURL = ( fileType, 1); let link = ('a)'; let link = ('a')
= "Screenshot image".
= imgURL.
(link);
(); let
(link);
})
// Mouse down
function mousedownInCanvasHandler(e){
currentPoint= { x: , y: }
// When the mouse is pressed we need to register the move and lift events
('mousemove', mousemoveInCanvasHandler)
('mouseup', mouseupInCanvasHandler)
}
// Draw the rectangle
function mousemoveInCanvasHandler(e){
let rectEndX =
let rectEndY =
// Get the width and height of the rectangle
let rectWidth = rectEndX -
let rectHeight = rectEndY -
let {width, height} = canvasNode
// Save the data for the screenshot area
screenshotData= [, , rectWidth, rectHeight]
(0, 0, width, height)
// Draw the mask
drawMask(0,0,width, height);
drawScreenShot(width, height,rectWidth, rectHeight)
}
// Draw the screen shot
function drawScreenShot( canvasWidth, canvasHeight,rectWidth,rectHeight){
// Draw a rectangle outside of the original shape.
= "destination-out".
= '#000'
(, ,rectWidth,rectHeight)
= 'destination-over'
// Draw a rectangle for the screenshot area
(img, 0, 0,canvasWidth, canvasHeight,0,0,canvasWidth, canvasHeight );
}
// Remove the move event and the lift event when the mouse is raised
function mouseupInCanvasHandler(e){
('mousemove', mousemoveInCanvasHandler)
('mouseup', mouseupInCanvasHandler)
drawScreenShotImg(screenshotData)
}
// Draw a screenshot of the area on the other canvas and display it
function drawScreenShotImg(screenshotData){
// screenshotData is the start and end coordinates of the screenshot.
let drawData = (... .screenshotData)
canvasSetWH(canvas2Box,screenshotData[2],screenshotData[3])
// Empty the canvas first, pay attention to the size of the empty, otherwise it will cause an overlay (not clean)
(0,0, , )
// Draw the screenshot area to canvas2
(drawData,0,0)
}
// Read the file
function readFile(e){
let file = [0]
// Get the type of the image, you'll need it when you download it later.
('', )
fileType =
getImageWH(file, function(width, height) {
// pass the width and height to the canvasSetWH function to display on the page
canvasSetWH(canvasNode,width, height)
(img, 0, 0,width, height ); // Call the method that draws the mask.
// Call the draw mask method
drawMask(0,0,width, height); // Call the drawMask method.
}); }
}
// Return the file (width and height of the image)
function getImageWH(file, callback) {
// Create a FileReader instance
const reader = new FileReader(); // Create a FileReader instance.
// Triggered when file reading is complete
= function(e) {
// e This object contains the properties associated with this image.
('e this object', e)
// Create a new Image object
// Set the src of the Image to the contents of the file being read.
= ;
// Triggered when the image is loaded
= function() {
// Call the callback function to return the image source, width, and height of the image.
callback(, );; // Call the callback function, returning the image source, width and height of the image.
}; }
}; }
// Start reading the contents of the file as a DataURL.
// The execution of the method requires the following call
(file); }
}
function canvasSetWH(canvasNode,width, height){
= width
= height
= "block"
}
// Draw the mask
function drawMask(x, y, width, height, opactity) {
= "rgba(0,0,0,0.5)"; function drawMask(x, y, width, height, opactity) {
(x, y, width, height); }
}
</script>.
</html>
coda
Finally finished writing, it's been a full week.
If you think the writing is good, ask your future bosses for a like, thanks!