Results demonstrate

Introduction of Canvas

This HTML element is designed for client-side vector graphics. It has no behavior of its own, but it presents a drawing API to the client JavaScript so that the script can draw whatever it wants to draw onto a canvas.

HTML5 tags are used to draw images (via scripts, usually JavaScript)

However, the element itself has no drawing capability (it’s just a container for graphics) – you must use scripts to do the actual drawing

The getContext() method returns an object that provides methods and properties for drawing on the canvas

This manual provides complete getContext(” 2D “) object properties and methods that can be used to draw text, lines, rectangles, circles, and more on a canvas

Differences between markup and SVG and VML:

One important difference between markup and SVG and VML is that there is a JavaScript based drawing API, whereas SVG and VML use an XML document to describe drawing.

The two methods are functionally equivalent, and either can be simulated with the other. On the surface, they are quite different, but each has its strengths and weaknesses. For example, AN SVG drawing is easy to edit by simply removing elements from its description.

To remove an element from a tag of the same graph, it is often necessary to erase the drawing and redraw it.

Introduction to Knowledge points

  • Create images using JS
let img = new Image()
// You can attach a link to the image
img.src = 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=826495019, & FM = 26 & gp = 0. 1749283937 JPG'
// Or the path of an existing image
//img.src = './download.jpg'

// Add to HTML
document.body.appendChild(img)
Copy the code

  • canvas.getContext(“2d”)

Syntax: The contextID parameter specifies the type you want to draw on the canvas. The only current legal value is “2d”, which specifies 2d drawing and causes the method to return an environment object that exports a 2D drawing API

let ctx = Canvas.getContext(contextID)
Copy the code

  • ctx.drawImage()

JavaScript syntax 1:

Position image on canvas:

context.drawImage(img,x,y);
Copy the code

JavaScript syntax 2:

Position the image on the canvas and specify the width and height of the image:

context.drawImage(img,x,y,width,height);
Copy the code

JavaScript syntax 3:

Clip the image and position the clipped part on the canvas:

context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);
Copy the code

  • ctx.getImageData()

The JavaScript syntax getImageData() method returns an ImageData object that copies the pixel data of the canvas’s specified rectangle.

For each pixel in the ImageData object, there is four-sided information, namely the RGBA value: R-red (0-255) G-green (0-255) B-blue (0-255) A-alpha channel (0-255; 0 is transparent, 255 is fully visible) Color /alpha exists as an array and is stored in the Data property of the ImageData object

var imgData=context.getImageData(x,y,width,height);
Copy the code

  • ctx.putImageData()

The putImageData() method puts the ImageData(from the specified ImageData object) back onto the canvas.

Now follow me through this little function step by step

step-by-step

Prepare our images and add our methods

<body>
    <img src="./download.jpg">
    <button onclick="addCanvas()">Generate the Canvas</button>
    <button onclick="generateImg()">Generate images</button>
</body>
Copy the code

Next I’ll write the addCanvas method

function addCanvas() {
		let bt = document.querySelector('button')

        let img = new Image();	//1. Prepare to assign a copy of the image
        img.src = './download.jpg'; 
        img.onload = function() { //2. Wait until the image is loaded
            let width = this.width
            let height = this.height
			
			let canvas = document.createElement('canvas') //3. Create canvas
			let ctx = canvas.getContext("2d");  //4. Get the contents of the canvas
        	canvas.setAttribute('width', width)  //5. For uniformity, set the width and height of the canvas to the width and height of the image
        	canvas.setAttribute('height', height)
   
            ctx.drawImage(this.0.0, width, height);  //5. Draw the image on the canvas

            document.body.insertBefore(canvas, bt) //5. Insert canvas in front of button}}Copy the code

Successfully get image on canvas:

Well, we’ve made a small success. What’s next? . Well, we need to make use of the native OnMouseup and OnMouseDown events that represent our mousedown process, so where do those two events go?

Yes, since we are going to Mosaic on the Canvas, we must add these two events to the Canvas element

Considering that the process of creating canvas is a bit more complicated, let’s do a module encapsulation.

function addCanvas() {
        let bt = document.querySelector('button')

        let img = new Image();
        img.src = './download.jpg'; // Put your own picture here
        img.onload = function() {
            let width = this.width
            let height = this.height

            let {
                canvas,
                ctx
            } = createCanvasAndCtx(width, height)  // Object destruct receives Canvas and CTX

            ctx.drawImage(this.0.0, width, height);

            document.body.insertBefore(canvas, bt)

        }
    }

    function createCanvasAndCtx(width, height) {
        let canvas = document.createElement('canvas')
        canvas.setAttribute('width', width)
        canvas.setAttribute('height', height)
        canvas.setAttribute('onmouseout'.'end()') // Fix the patch where the mouse does not leave the canvas
        canvas.setAttribute('onmousedown'.'start()')  // Add mouse press
        canvas.setAttribute('onmouseup'.'end()')	// Add mouse popup
        let ctx = canvas.getContext("2d");
        return {
            canvas,
            ctx
        }
    }

	function start() {
            let canvas = document.querySelector('canvas')
            canvas.onmousemove = () = > {
                console.log('You pressed and moved the mouse.')}}function end() {
            let canvas = document.querySelector('canvas')
            canvas.onmousemove = null
        }
Copy the code

Let’s test oursstart()andend()Does it work?Well, so far, our code is still working as expected

The next challenge is to get the pixels and manipulate them, so let’s rewrite the start() function


function start() {
    let img = document.querySelector('img')
    let canvas = document.querySelector('canvas')
    let ctx = canvas.getContext("2d");
    imgData = ctx.getImageData(0.0, img.clientWidth, img.clientHeight);
    canvas.onmousemove = (e) = > {
        let w = imgData.width; //1. Get the image width and height
        let h = imgData.height;

        // The degree of Mosaic, the larger the number, the more blurred
        let num = 10;

        // Get the current mouse pixel RGBA
        let color = getXY(imgData, e.offsetX, e.offsetY);

        for (let k = 0; k < num; k++) {
            for (let l = 0; l < num; l++) {
                ImgData // Set the color of the imgData coordinate (e.off + l, e.off + k)setXY(imgData, e.offsetX + l, e.offsetY + k, color); }}// Update canvas data
        ctx.putImageData(imgData, 0.0); }}// The setXY and getXY functions are provided for you. If you are interested, you can explore the principle of fetching
function setXY(obj, x, y, color) {
    var w = obj.width;
    var h = obj.height;
    var d = obj.data;
    obj.data[4 * (y * w + x)] = color[0];
    obj.data[4 * (y * w + x) + 1] = color[1];
    obj.data[4 * (y * w + x) + 2] = color[2];
    obj.data[4 * (y * w + x) + 3] = color[3];
}

function getXY(obj, x, y) {
    var w = obj.width;
    var h = obj.height;
    var d = obj.data;
    var color = [];
    color[0] = obj.data[4 * (y * w + x)];
    color[1] = obj.data[4 * (y * w + x) + 1];
    color[2] = obj.data[4 * (y * w + x) + 2];
    color[3] = obj.data[4 * (y * w + x) + 3];
    return color;
}
Copy the code

Well, we’re close, and the last step is to generate the image

Fortunately, Canavs gives us a straightforward way to export the canvas directly as a Base64 encoded image:

function generateImg() {
    let canvas = document.querySelector('canvas')
    var newImg = new Image();
    newImg.src = canvas.toDataURL("image/png");
    document.body.insertBefore(newImg, canvas)
}
Copy the code

End result:

Let’s see if your handwritten code looks like the following:

The complete code

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, > <title>Document</title> </head> <body> <body> <img SRC =" <button onclick="generateImg()"> Generate Canvas</button> </button> </body> <script> function addCanvas() { let bt = document.querySelector('button') let img = new Image(); img.src = './download.jpg'; Img. onload = function() {let width = this.width let height = this.height let {canvas, ctx } = createCanvasAndCtx(width, height) ctx.drawImage(this, 0, 0, width, height); document.body.insertBefore(canvas, bt) } } function createCanvasAndCtx(width, height) { let canvas = document.createElement('canvas') canvas.setAttribute('width', width) canvas.setAttribute('height', height) canvas.setAttribute('onmouseout', 'end()') canvas.setAttribute('onmousedown', 'start()') canvas.setAttribute('onmouseup', 'end()') let ctx = canvas.getContext("2d"); return { canvas, ctx } } function start() { let img = document.querySelector('img') let canvas = document.querySelector('canvas') let ctx  = canvas.getContext("2d"); imgData = ctx.getImageData(0, 0, img.clientWidth, img.clientHeight); canvas.onmousemove = (e) => { let w = imgData.width; Imgdata. height; //1. // let num = 10; RGBA let color = getXY(imgData, e.off, e.off); for (let k = 0; k < num; k++) { for (let l = 0; l < num; ImgData setXY(imgData, e.off + l, e.off + k, color) {// Set imgData's color to (e.off + l, e.off + k, color); // Update canvas data ctx.putImageData(imgData, 0, 0); } } function generateImg() { let canvas = document.querySelector('canvas') var newImg = new Image(); newImg.src = canvas.toDataURL("image/png"); document.body.insertBefore(newImg, canvas) } function setXY(obj, x, y, color) { var w = obj.width; var h = obj.height; var d = obj.data; obj.data[4 * (y * w + x)] = color[0]; obj.data[4 * (y * w + x) + 1] = color[1]; obj.data[4 * (y * w + x) + 2] = color[2]; obj.data[4 * (y * w + x) + 3] = color[3]; } function getXY(obj, x, y) { var w = obj.width; var h = obj.height; var d = obj.data; var color = []; color[0] = obj.data[4 * (y * w + x)]; color[1] = obj.data[4 * (y * w + x) + 1]; color[2] = obj.data[4 * (y * w + x) + 2]; color[3] = obj.data[4 * (y * w + x) + 3]; return color; } function end() { let canvas = document.querySelector('canvas') canvas.onmousemove = null } </script> </body> </html>Copy the code

Of course, you can do more, such as the Mosaic above is square, you can use your mathematical knowledge to make it into a circle, with the center of the mouse spread

You can also choose to improve some of the process, such as Mosaic placement is wrong, you can choose to clean the canvas and start again ~ or do some cleaning, export the image and hide the canvas

If you are also in the front of learning, if this article helps you, welcome to like favorites and follow, there will be more quality content