图片中心对齐显示在固定宽高的容器中
- 需求:图片横向或纵向至少有一个方向显示全部内容
注意:容器为固定宽高,图一宽高比小于1,图二宽高比大于1
- 如图一,图片的宽高比小于1,此时需要将图片的横向全部内容显示。如果图片的宽度大于等于容器的宽度,需要以容器的固定宽度为基准值对图片的纵向等比例缩小;如果图片的宽度小于容器的宽度,需要以容器的固定宽度为基准值对图片的纵向等比例放大;
- 如图二,图片的宽高比大于等于1,此时需要将图片的纵向全部内容显示。如果图片的高度大于等于容器的高度,需要以容器的固定高度为基准值对图片的横向等比例缩小;如果图片的高度小于容器的高度,需要以容器的固定高度为基准值对图片的横向等比例放大;
将网络图片加载到本地
- 获取图片原始宽高
let url = "https://www.wanshaobo.com/static/1.png";
var img = new Image();
img.src = url;
img.onload = function(){
//图片原始宽高
let w = img.width;
let h = img.height;
}
对图片进行裁剪
- drawImage(image, x1, y1,w1, h1, x2, y2, w2, h2) 截取图片固定区域绘制在canvas上
//DOM 布局
<canvas id="canvas" width="590" height="328" style="width:295px;height:164px;background:#00ffff"/>
let url = "https://www.wanshaobo.com/static/1.png";
const ctx = dd.createCanvasContext('canvas');
//图片原始宽高
let w;
let h;
//图片裁剪的起始坐标
let startX = 0;
let startY = 0;
//图片裁剪后的宽高
let clipW = 0;
let clipH = 0;
//canvas容器的宽高
let canvasW = 295;
let canvasH = 164;
//canvas容器的宽高比
let canvasRatio = canvasW / canvasH;
//drawImage(image, x1, y1,w1, h1, x2, y2, w2, h2) 参数介绍
//(x1, y1)和(w1, h1)是裁剪图片的起始坐标和宽高
//(x2, y2)和(w2, h2)是图片在画布上绘制的起始坐标和画布为图片开辟的可用宽高
ctx.drawImage(url, startX, startY, clipW, clipH, 0, 0, canvasW*2, canvasH*2);
将canvas容器内容转化为图片临时url路径
ctx.toTempFilePath({
success(res) {
console.log(res.filePath);// http://resource/******.image
}
});
将图片临时url路径上传到服务器
let url = "http://resource/******.image";
dd.uploadFile({
url:'请使用自己服务器地址',
fileType: 'image',
fileName: 'file',
filePath: url,
success: (res) => {}
});
完整工程实例
注意:canvas 尺寸,移动端使用二倍尺寸,PC端使用单倍尺寸
- DOM
<canvas id="canvas" width="590" height="328" style="width:295px;height:164px;background:#00ffff"/>
- CSS
#canvas{
position: absolute;
top: -999rpx;
}
- JS
/**
* 采用canvas异步裁剪图片
* @param url
* @return promise实例 then方法会拿到裁剪后的图片url
*/
function ayncClipImage(url) {
return new Promise((resolve,reject)=>{
const ctx = dd.createCanvasContext('canvas');
var img = new Image();
img.src = url;
img.onload = function(e) {
//图片原始宽高
let w = img.width;
let h = img.height;
//图片裁剪的起始坐标
let startX = 0;
let startY = 0;
//图片裁剪后的宽高
let clipW = 0;
let clipH = 0;
//canvas容器的宽高
let canvasW = 295;
let canvasH = 164;
//canvas容器的宽高比
let canvasRatio = canvasW / canvasH;
//图片宽度大于等于高度
if(w >= h){
clipW = canvasRatio * h;
clipH = h;
startX = (w - clipW) / 2;
startY = 0;
}else{
clipW = w;
clipH = w / canvasRatio;
startX = 0;
startY = (h - clipH) / 2;
}
//drawImage(image, x1, y1, w1, h1, x2, y2, w2, h2) 参数介绍
//(x1, y1)和(w1, h1)是裁剪图片的起始坐标和宽高
//(x2, y2)和(w2, h2)是图片在画布上绘制的起始坐标和画布为图片开辟的可用宽高
ctx.drawImage(url, startX, startY, clipW, clipH, 0, 0, canvasW*2, canvasH*2)
// setTimeout(()=>{ctx.draw();},500);
ctx.toTempFilePath({
success(res) {
resolve(res.filePath)
},
});
}
});
}
//使用
let url = "https://www.wanshaobo.com/static/1.png";
ayncClipImage(url).then((res)=>{
console.log(res);// http://resource/******.image
});