Home > Article > Web Front-end > How to use canvas to implement custom avatar function
This time I will show you how to use canvas to implement the custom avatar function, and what are the precautions for using canvas to implement the custom avatar function. The following is a practical case, let's take a look.
Write it first:
Two days ago, the boss told me that the custom avatar function on Tiger’s official website is implemented in flash, and there is no If you have installed it, you have to manually "allow" flash to run. So I was asked to use canvas to implement the same function. Hehe, I happened to be studying canvas recently, so I happily agreed (actually, wouldn’t you agree if you haven’t studied it, hahahahaha~)
Result display:
Git address:https://github.com/ry928330/portraitDIY
Function description:
#Drag the small box on the left, or place the mouse on the lower right corner of the small box and click When the box is stretched, the image covered by the box is automatically captured and then redrawn in multiple containers on the right.
Enter the width and height to customize the avatar size you need. Currently, only avatar images with the same width and height are supported.
Implementation details:
Because you want to take a screenshot of the area where the picture is located, you have to make a canvas, covering the area where the image is located. Here, we give a function to create a canvas at the same position based on the class name of the element in the passed in DOM, and cover it on the original DOM element:
function createCanvasByClassName(tag) { var canvasInitialWidth = $('.' + tag).width(); var canvasInitialHeight = $('.' + tag).height(); var left = $('.' + tag).offset().left - $('.' + tag).parent('.portraitContainer').offset().left + 1; var top = $('.' + tag).offset().top - $('.' + tag).parent('.portraitContainer').offset().top + 1; //var left = $('.' + tag).offset().left + 1; //var top = $('.' + tag).offset().top + 1; clearCanvasObj.left = $('.' + tag).offset().left + 1; clearCanvasObj.top = $('.' + tag).offset().top + 1; // clearCanvasObj.left = left; // clearCanvasObj.top = top; var canvasElement = $('<canvas></canvas>'); var randomNum = Math.floor(getRandom(0, 10000)); clearCanvasObj.canvasId = randomNum; canvasElement.attr({ id: 'canvas', width: canvasInitialWidth, height: canvasInitialHeight }); canvasElement.css({ position: 'absolute', top: top, left: left }); //$('body').append(canvasElement); var appendEle = $('.portraitContainer').append(canvasElement); var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); //ctx.fillStyle = "rgba(211,211,216,0.5)"; ctx.clearRect(0, 0, canvasInitialWidth, canvasInitialHeight); ctx.fillStyle = "rgba(0,0,0, 0.4)"; ctx.fillRect(0, 0, canvasInitialWidth, canvasInitialHeight); return canvas; }
With this canvas you can The area where the picture is located has been manipulated wantonly. First, paint the entire area with a light black shadow, and then erase the color inside the initial small box area. Then add mousedown, mousemove, and mouseup events to the entire page. The functions they do are similar to the drag and drop function you implement on the page. Here we focus on the operations done in mousemove. The code is as follows:
function mousemoveFunc(event) { /* Act on the event */ var nowMouseX = event.clientX - clearCanvasObj.left; var nowMouseY = event.clientY - clearCanvasObj.top; if (nowMouseX >= clearCanvasObj.xStart && nowMouseX <= clearCanvasObj.xStart + clearCanvasObj.width && nowMouseY >= clearCanvasObj.yStart && nowMouseY <= clearCanvasObj.yStart + clearCanvasObj.height) { clearCanvasObj.isCanvasArea = true; //clearCanvasObj.isRightCorner = false; imgContainerCanvas.style.cursor = 'move'; } else if ((nowMouseX >= clearCanvasObj.xStart + clearCanvasObj.width - 10) && (nowMouseX <= clearCanvasObj.xStart+ clearCanvasObj.width + 10) && (nowMouseY >= clearCanvasObj.yStart + clearCanvasObj.height - 10) && (nowMouseY <= clearCanvasObj.yStart + clearCanvasObj.height + 10)) { clearCanvasObj.isCanvasArea = true; //clearCanvasObj.beginDraw = false; imgContainerCanvas.style.cursor = 'se-resize'; } else { clearCanvasObj.isCanvasArea = false; //clearCanvasObj.isRightCorner = false; imgContainerCanvas.style.cursor = 'default'; } var outerDomWidth = $(".imgContainer").width(); var outerDomHeight = $(".imgContainer").height(); var xDistance = event.clientX - clearCanvasObj.mouseX; var yDistance = event.clientY - clearCanvasObj.mouseY; //var outerCTX = canvas.getContext('2d'); //移动小方框 if (clearCanvasObj.beginDraw && clearCanvasObj.isCanvasArea && !clearCanvasObj.isRightCorner) { ry_CTX.fillStyle = clearCanvasObj.color; // console.log('1', clearCanvasObj.xStart, clearCanvasObj.yStart) ry_CTX.fillRect(clearCanvasObj.xStart, clearCanvasObj.yStart, clearCanvasObj.width, clearCanvasObj.height); //outerCTX.fillRect(0, 0, canvas.width, canvas.height); clearCanvasObj.xStart += xDistance; clearCanvasObj.yStart += yDistance; //判断方框是否达到边界 if (clearCanvasObj.xStart <= 0) { clearCanvasObj.xStart = 0; } if (clearCanvasObj.yStart <= 0) { clearCanvasObj.yStart = 0; } if ((clearCanvasObj.xStart + clearCanvasObj.width) >= outerDomWidth) { clearCanvasObj.xStart = outerDomWidth - clearCanvasObj.width; } if ((clearCanvasObj.yStart + clearCanvasObj.height) >= outerDomHeight) { clearCanvasObj.yStart = outerDomHeight - clearCanvasObj.height; } // console.log('2', clearCanvasObj.xStart, clearCanvasObj.yStart) ry_CTX.clearRect(clearCanvasObj.xStart, clearCanvasObj.yStart, clearCanvasObj.width, clearCanvasObj.height); produceSmallPic(clearCanvasObj.xStart+clearCanvasObj.left, clearCanvasObj.yStart+clearCanvasObj.top, clearCanvasObj.width, clearCanvasObj.height, imageURL) clearCanvasObj.mouseX = event.clientX; clearCanvasObj.mouseY = event.clientY; } //拖拽小方框 if (clearCanvasObj.isRightCorner) { ry_CTX.fillStyle = clearCanvasObj.color; ry_CTX.fillRect(clearCanvasObj.xStart, clearCanvasObj.yStart, clearCanvasObj.width, clearCanvasObj.height); var realDistance = Math.min(xDistance, yDistance) clearCanvasObj.width += realDistance; clearCanvasObj.height += realDistance; //拖动时边界条件的判断 if (clearCanvasObj.xStart + clearCanvasObj.width >= outerDomWidth) { clearCanvasObj.width = outerDomWidth - clearCanvasObj.xStart; clearCanvasObj.height = outerDomWidth - clearCanvasObj.xStart; } if (clearCanvasObj.yStart + clearCanvasObj.height >= outerDomHeight) { clearCanvasObj.width = outerDomHeight - clearCanvasObj.yStart; clearCanvasObj.height = outerDomHeight - clearCanvasObj.yStart; } if (clearCanvasObj.width <= 10) { clearCanvasObj.width = 10; } if (clearCanvasObj.height <= 10) { clearCanvasObj.height = 10; } ry_CTX.clearRect(clearCanvasObj.xStart, clearCanvasObj.yStart, clearCanvasObj.width, clearCanvasObj.height); produceSmallPic(clearCanvasObj.xStart+clearCanvasObj.left, clearCanvasObj.yStart+clearCanvasObj.top, clearCanvasObj.width, clearCanvasObj.height, imageURL); clearCanvasObj.mouseX = event.clientX; clearCanvasObj.mouseY = event.clientY; } }
In the function, you need to pay attention to the boundary conditions of dragging. One is that the box cannot be dragged to the boundary outside the DOM where the picture is located; the other is that when your mouse is placed in the area where the small box is, the style of the mouse is changed. During the dragging process of the box, we continuously redraw the moving area of the box (that is, continuously draw shadows), and then call the clearRect function at the new position to re-wipe out a small box. During the dragging or stretching process, we will continuously call the produceSmallPic function to continuously redraw the required avatar according to the container size in the container on the right (each container is a canvas). The code is as follows:
function produceSmallPic(imageURL,left, top, width, height) { var img = new Image(); img.src = imageURL; var targetCtx = new Array(); var targetCanvas = null; img.onload = function() { portraitGroupsArr.forEach(function(item, index) { targetCanvas = document.getElementById(item.class); targetCtx.push(targetCanvas.getContext('2d')); targetCtx[index].clearRect(0,0, item.width, item.height); targetCtx[index].drawImage(img, left - clearCanvasObj.left, top - clearCanvasObj.top, width, height, 0, 0 , item.width, item.height); }) } }
Let’s talk about the role of this function. Here we need to pay attention to a parameter imageURL. This URL is converted from the DOM where the image is located. Because you need to turn the area where the DOM is located into a picture, so that you can use the drawImage function to capture the area you need. So we first use the html2canvas library function to convert the DOM where the image is located into canvas. The content of this canvas contains the image you want to intercept, and then convert this canvas into an image to obtain the image address imageURL. The code is as follows:
html2canvas(document.getElementById('imgContainer'), { onrendered: function(canvas) { var imageURL = canvasTransToImage(canavs); ... } }) function canvasTransToImage(canvas) { var imageURL = canvas.toDataURL('image/png'); return imageURL; }
Then, you can use the canvas container on the right and return the image to it. The whole process ends like this. Looking back, it is not very simple.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
H5 implements custom path animation in Canvas
The above is the detailed content of How to use canvas to implement custom avatar function. For more information, please follow other related articles on the PHP Chinese website!