Home > Article > Web Front-end > Detailed introduction to HTML5 Canvas image and text code for processing avatar uploads
Recently, the community system needs to support the mobile terminal, which involves the uploading of user avatars. The avatars come in three sizes: large, medium and small. On the PC side, the community uses Flash to handle avatar editing and generation, but the Flash control The interface is unfriendly and the mobile terminal does not support Flash well. Considering these problems, we finally chose Canvas to complete image size scaling and image data acquisition.
Avatars are generally square. First, we need to get the minimum value of the width and height of the image, and use the minimum value as the side length to center-crop the image, and finally get a square image. :
var ImageEditor = function() { // 用离线canvas处理图片数据 this.canvas = document.createElement('canvas'); this.context = this.canvas.getContext('2d'); }; var fn = ImageEditor.prototype; fn.resizeCanvas = function(width, height) { this.canvas.width = width; this.canvas.height = height; }; fn.clipSquareImage = function(url, callback) { var that = this, img = new Image(); img.src = url; img.onload = function() { // 取宽高最小值作为正方形边长 var eLength = Math.min(img.width, img.height), picture = img; // canvas不支持局部截屏,截屏前必须先调节canvas的宽高 that.resizeCanvas(eLength, eLength); // 将图片以居中裁剪的方式画到canvas中。 // drawImage支持9个参数:图片对象,图片上的剪切坐标XY, // 剪切宽高,图片在canvas上的坐标XY及图片宽高 that.context.drawImage(picture, (picture.width - eLength) / 2, (picture.height - eLength) / 2, eLength, eLength, 0, 0, eLength, eLength); // 截屏,即获取base64数据 callback.call(that, that.canvas.toDataURL('image/png')); }; };
In the above clipSquareImage
function, since the canvas.toDataURL
interface does not provide width and height parameters, it can only be used once Capture the screen data of the entire canvas, so before taking a screenshot of the Canvas, we must first set the size of the Canvas element. However, the resolution of mobile photos is extremely high, and the width and height are mostly above 3000. When we set the size of the Canvas based on the minimum width and height of the photo, the minimum width of the Canvas element is also as high as above 3000.
The problem is that each platform has limitations on the size of Canvas. If any value of the width or height of Canvas exceeds the platform limit, Canvas will not be able to render. canvas.toDataURL
only A transparent image data can be obtained.
Maximum size of a canvas element mentions the size limit of Canvas under some platforms:
chrome = 32767x32767 iPod Touch 16GB = 1448x1448 iPad Mini = 2290x2289 iPhone 3 = 1448x1448 iPhone 5 = 2290x2289
Referring to the above data, we first set a maximum width for Canvas:
var MAX_WIDTH = 1000;
Add maximum width detection to the clipSquareImage
function. If it exceeds the limit, create a temporary canvas for image scaling, and finally center-cut the temporary Canvas:
fn.clipSquareImage = function(url, callback) { var that = this, img = new Image(); img.src = url; img.onload = function() { // 取图片宽高和Canvas的最大宽度的最小值作为等边长 var eLength = Math.min(img.width, img.height, MAX_WIDTH), // 剪切对象 picture = img, tempEditor, ratio; // 如果图片尺寸超出限制 if (eLength === MAX_WIDTH) { // 创建一个临时editor tempEditor = new ImageEditor(); ratio = img.width / img.height; // 按图片比例缩放canvas img.width < img.height ? tempEditor.resizeCanvas(MAX_WIDTH * ratio, MAX_WIDTH) : tempEditor.resizeCanvas(MAX_WIDTH, MAX_WIDTH / ratio); tempEditor.context.drawImage(img, 0, 0, tempEditor.canvas.width, tempEditor.canvas.height); // 将临时Canvas作为剪切对象 picture = tempEditor.canvas; eLength = Math.min(tempEditor.canvas.width, tempEditor.canvas.height); } // 居中剪切 // ... ... // 截屏操作 // ... ... }; };
Above we have been able to crop a square picture through Canvas. Next we need to deal with the three sizes of avatar pictures: large, medium and small. In Canvas, the drawImage
interface provides a very convenient scaling function:
var editor = new ImageEditor; // 将图片缩放到300x300 // drawImage支持5个参数:图片对象,及图片在canvas上的坐标和宽高 editor.context.drawImage(squareImage, 0, 0, 300, 300);
However, directly using drawImage
to reduce large-size images will cause the image to appear jagged. On stack overflow, HTML5 canvas drawImage: how to apply antialiasing proposed a solution: reduce the image several times in equal proportions, and finally enlarge it to the target size:
Reference With this solution, we can implement the antialiasScale
anti-aliasing scaling function:
fn.antialisScale = function(img, width, height) { var offlineCanvas = document.createElement('canvas'), offlineCtx = offlineCanvas.getContext('2d'), sourceWidth = img.width, sourceHeight = img.height, // 缩小操作的次数 steps = Math.ceil(Math.log(sourceWidth / width) / Math.log(2)) - 1, i; // 渲染图片 offlineCanvas.width = sourceWidth; offlineCanvas.height = sourceHeight; offlineCtx.drawImage(img, 0, 0, offlineCanvas.width, offlineCanvas.height); // 缩小操作 // 进行steps次的减半缩小 for(i = 0; i < steps; i++) { offlineCtx.drawImage(offlineCanvas, 0, 0, offlineCanvas.width * 0.5, offlineCanvas.height * 0.5); } // 放大操作 // 进行steps次的两倍放大 this.context.drawImage(offlineCanvas, 0, 0, offlineCanvas.width * Math.pow(0.5, steps), offlineCanvas.height * Math.pow(0.5, steps), 0, 0, width, height); };
We can use this function instead of drawImage to complete the scaling work and generate three sizes of avatar images:
fn.scaleSquareImage = function(url, sizes, callback) { var that = this; // 先裁剪一个正方形 that.clipSquareImage(url, sizes, function(data) { var squareImage = new Image(), result = [], i; squareImage.src = data; // 抗锯齿缩放 for (i = 0; i < sizes.length; i++) { that.antialisScale(squareImage, sizes[i], size[i]); result.push(that.canvas.toDataURL('image/png')); } callback.call(that, result); }); };
Canvas.toDataURL()
The default image data format obtained is: data:image/png;base64,
+ base64 data:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC
When the Canvas screenshot data is transmitted to the backend, the backend needs to truncate the starting field data:image/png;base64,
to obtain the real base64 data behind:
<?php $imgData = $_POST['imgData']; // 截取有用的部分 list($type, $imgData) = explode(';', $imgData); list(, $imgData) = explode(',', $imgData); // base64 编码中使用了加号, // 如果通过url传递base64数据,+号会转换成空格 $imgData = str_replace(' ', '+', $imgData); // 存储文件 $success = file_put_contents('PATH/XXX.png', base64_decode($imgData));
Save a Base64 Encoded Canvas image to a png file using PHP
#