您的位置:首页 > 其它

image大图缩小转成canvas后锯齿的问题

2016-05-18 15:24 225 查看
最近在项目中做到头像本地处理的时候发现一个问题,就是上传的头像源图如果比较大,会导致生成后的头像锯齿比较明显。

为了解决这个问题,网上搜了好多资料,很多都是说不断的缩小图片然后再放大图片,再渲染到canvas,这个方案试过了,但是无论从效率还是效果上都不太尽人意。

后来不小心在github上发现了一个小插件,还真好用,完美的把问题解决了。

这里要感谢一下插件作者,再帮他宣传一下。

插件地址:https://github.com/sapics/scale.js

头像上传处理思路是这样的:

1)<input type'File">接收图片上传

2)把源图片裁剪成目标宽高比例(这里不缩放,一缩放就会有锯齿了)

3)用scale.js插件把裁剪后的图像缩小到目标头像大小

4)canvas.toDataURL()获取目标图像urlBase64,完成

附上代码片断

var imgLogo = new Image();
imgLogo.src = _this._config.logo;
imgLogo.onload = function() {
_this._ctx.drawImage(imgLogo, 0, 0, _this._config.logoWidth, _this._config.signHeight);

var imgAvatar = new Image();
imgAvatar.src = _this._config.avatar;
imgAvatar.onload = function() {
var sx = 0, sy = 0,
sw = this.width, sh = this.height,
dx = _this._config.logoWidth, dy = 0,
dw = _this._config.avatarWidth, dh = _this._config.signHeight;

var deltaD = dw / dh,
deltaS = sw / sh;

if(deltaD > deltaS) { // 高图
var oldSh = sh;
sh = (dh / dw) * sw;

// 取中间
if(oldSh > sh) {
sy = (oldSh - sh) / 2;
}
} else if(deltaD < deltaS) { // 横图
var oldSw = sw;
sw = (dw / dh) * sh;

// 取中间
if(oldSw > sw) {
sx = (oldSw - sw) / 2;
}
}

// _this._ctx.globalCompositeOperation = 'source-atop';

// 先裁剪
var tCanvas = document.createElement('canvas'),
tContext = tCanvas.getContext('2d');
tCanvas.width = Math.floor(sw);
tCanvas.height = Math.floor(sh);
tContext.drawImage(imgAvatar, Math.floor(sx), Math.floor(sy), Math.floor(sw), Math.floor(sh), 0, 0, Math.floor(sw), Math.floor(sh));

// 再缩小
// 对要计算的值,先取整后再绘图,可以提高效率
var scaleImage  = scale({width: Math.floor(dw), height: Math.floor(dh)}, tCanvas, 'jpeg');

_this._ctx.drawImage(scaleImage, Math.floor(dx), Math.floor(dy), Math.floor(dw), Math.floor(dh));

if(typeof callback === 'function') {
callback(_this._canvas.toDataURL());
}
};
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: