preface
Canvas is a newly added technology in H5, which is mainly used in image processing and animation drawing. As more and more Canvas scenes are used, it is of great benefit to understand Canvas in daily development. This article will introduce the basic picture operation and processing of Canvas
Picture uploading and drawing
Uploading and drawing pictures to Canva is the most common Canvas image processing. How is this uploading and drawing process realized? Here’s an example:
<canvas id="myCanvas"></canvas>
<input type="file" id="file">
Copy the code
let upload = document.getElementById('file')
upload.onchange = (event) = > {
let file = event.target.files[0]
let fileReader = new FileReader()
fileReader.onload = (e) = > {
let img = new Image()
img.src = e.target.result
img.onload = (a)= > {
let canvas = document.getElementById('myCanvas')
canvas.width = img.width
canvas.height = img.height
let context = canvas.getContext('2d')
context.drawImage(img, 0.0)
}
}
fileReader.readAsDataURL(file)
}
Copy the code
The upload and draw process can be summarized in two steps:
- Convert the input uploaded File object into a Base64 image via the FileReader object
- Create an Image object and draw it on the canvas
Why copy the base64 address to the Image object and then draw the Image object to Canvas instead of drawing it directly? This is because Canvas does not support URL as image source when drawing. Canvas only supports the following image source:
- Constructed by the Image() function or whateverThe element
- The
- Another
- High-performance bitmap as image source
There is another point that Canvas needs to pay attention to when drawing: When Canvas draws pictures under different domain names, cross-domain errors may occur, as shown in the figure:
- Add access-Control-allow-origin to * or specify a domain name for the image server response header
- Set the crossOrigin attribute for Image img.setAttribute(“crossOrigin”,’Anonymous’)
Simple sample code:
let img = new Image()
img.setAttribute("crossOrigin".'Anonymous')
img.src = './images/avatar.jpeg'
img.onload = (a)= > {
let canvas = document.getElementById('myCanvas')
canvas.width = img.width
canvas.height = img.height
let context = canvas.getContext('2d')
context.drawImage(img, 0.0)
console.log(canvas.toDataURL('image/png'.1.0))}Copy the code
More cross-domain content can be found here
Image transform
zooming
Zooming in the Canvas is actually through the Canvas zoom to achieve, so the default zoom center is the Canvas origin (0, 0), but usually we do the zoom all want image center is located at the center of the zoom here are two ways to achieve image center as the center of the zoom zoom effect, then respectively the two ways of sample: The first:
let canvas = document.getElementById('myCanvas')
canvas.width = img.width
canvas.height = img.height
let context = canvas.getContext('2d')
context.translate(img.width / 2, img.height / 2)
context.scale(0.5.0.5)
context.translate(-img.width / 2, -img.height / 2)
context.drawImage(img, 0.0, img.width, img.height)
Copy the code
The first method is canvas translation. First, move the origin of the canvas to the center of the image, then scale the canvas, then translate the canvas back, and finally draw the picture. At this time, the drawn picture is scaled with the center of the picture
The second:
let canvas = document.getElementById('myCanvas')
canvas.width = img.width
canvas.height = img.height
let context = canvas.getContext('2d')
let paintWidth = img.width / 2
let paintHight = img.height / 2
let originX = 0 // The x-coordinate of the original image
let originY = 0 // The original image is Y coordinate
let paintX = originX + (img.width - paintWidth) / 2 // Zoom the image X coordinate
let paintY = originY + (img.height - paintHight) / 2 // The Y coordinate of the scaled image
context.drawImage(img, paintX, paintY, paintWidth, paintHight)
Copy the code
The second method is the most direct calculation of the position offset generated by the zoomed picture with the upper left corner as the zoom center, and the position offset is added to the drawing of the picture
Image rotation
Picture rotation of Canvas is the same as picture zooming. The default rotation center is also the origin of the Canvas (0, 0). In this case, the Canvas needs to be shifted to realize the center rotation of the picture, for example
let img = new Image()
img.setAttribute("crossOrigin".'Anonymous')
img.src = './images/avatar.jpeg'
img.onload = (a)= > {
let canvas = document.getElementById('myCanvas')
canvas.width = img.width
canvas.height = img.height
let context = canvas.getContext('2d')
context.translate(img.width / 2, img.height / 2)
context.rotate(30 * Math.PI / 180)
context.translate(-img.width / 2, -img.height / 2)
context.drawImage(img, 0.0, img.width, img.height)
}
Copy the code
Image transform
The image transformation can take the vertical Central Line as the axis of symmetry, and the transformation of left and right images is called horizontal mirror, or the horizontal Central Line as the axis of symmetry, and the transformation of the upper and lower images is called vertical mirror. Generally, horizontal mirror is used more, here is an example of horizontal mirror:
let img = new Image()
img.setAttribute("crossOrigin".'Anonymous')
img.src = './images/avatar.jpeg'
img.onload = (a)= > {
let canvas = document.getElementById('myCanvas')
canvas.width = img.width
canvas.height = img.height
let context = canvas.getContext('2d')
context.translate(img.width / 2, img.height / 2)
context.scale(- 1 , 1)
context.translate(-img.width / 2, -img.height / 2)
context.drawImage(img, 0.0, img.width, img.height)
}
Copy the code
The original:
The principle of the mirror operation is very simple: set the scale to a negative value. When the X-axis scale is negative, it is a horizontal mirror, and when the Y-axis scale is negative, it is a vertical mirror
Symmetry axis reversal
Symmetry axis flip refers to the diagonal flip of the image from the top left to the bottom right. Let’s see how this is done using code Canvas:
let img = new Image()
img.setAttribute("crossOrigin".'Anonymous')
img.src = './images/avatar.jpeg'
img.onload = (a)= > {
let canvas = document.getElementById('myCanvas')
canvas.width = img.width
canvas.height = img.height
let context = canvas.getContext('2d')
context.translate(img.width / 2, img.height / 2)
context.scale(- 1 , 1)
context.rotate(90 * Math.PI / 180)
context.translate(-img.width / 2, -img.height / 2)
context.drawImage(img, 0.0, img.width, img.height)
}
Copy the code
Flip chart:
How it works: Mirror horizontally first, then rotate 90 degrees clockwise. Due to the first horizontal mirror, the coordinate axes will be flipped horizontally. Rotating 90 degrees clockwise is actually rotating 90 degrees anticlockwise
Image gray scale
Grayscale effect of pictures is a very common image processing effect of Canvas. Let’s first look at the code to achieve grayscale effect:
let img = new Image()
img.setAttribute("crossOrigin".'Anonymous')
img.src = './images/avatar.jpeg'
img.onload = (a)= > {
let canvas = document.getElementById('myCanvas')
canvas.width = img.width
canvas.height = img.height
let context = canvas.getContext('2d')
context.drawImage(img, 0.0, img.width, img.height)
let imageData = context.getImageData(0.0, img.width, img.height)
let data = imageData.data
for (let i = 0; i < data.length; i += 4) {
let average = (data[i] + data[i + 1] + data[i + 2) /3
data[i] = average
data[i + 1] = average
data[i + 2] = average
}
context.putImageData(imageData, 0.0)}Copy the code
Grayscale rendering:
- First draw the image on the canvas
- The getImageData method is used to obtain the RGB value of each pixel
- Calculate the RGB average value of each pixel point and reassign the value
- Draw the recalculated imageData object onto the image using putImageData
For those of you who are not familiar with the getImageData and putImageData apis, you can click on getImageDataputImageData
conclusion
Canva plays an increasingly prominent role in image processing, so I wrote this article to give a brief introduction to the basic image operation and processing of Canvas, hoping that reading this article can help you to understand Canvas. If there is a mistake or not rigorous place, welcome criticism and correction, if you like, welcome to praise