在canvas绘图时,通常会遇到的一种情况是用固定宽高来显示图片,如果直接把图片内容填充进去的话,显示出来的图片就会被压扁或者被挤瘦,其效果简直不忍直视!那么,就需要把图片进行拉伸、压缩或裁剪。
接下来,先给 drawImage 做个介绍:
canvas的drawImage函数可以 绘制图像到画布。
它有以下参数:
参数 | 类型 | 说明 |
---|---|---|
imageResource | String | 所要绘制的图片资源 |
dx | Number | 图像的左上角在目标 canvas 上 x 轴的位置 |
dy | Number | 图像的左上角在目标 canvas 上 y 轴的位置 |
dWidth | Number | 在目标画布上绘制图像的宽度,允许对绘制的图像进行缩放 |
dHeight | Number | 在目标画布上绘制图像的高度,允许对绘制的图像进行缩放 |
sx | Number | 源图像的矩形选择框的左上角 x 坐标 |
sy | Number | 源图像的矩形选择框的左上角 y 坐标 |
sWidth | Number | 源图像的矩形选择框的宽度 |
sHeight | Number | 源图像的矩形选择框的高度 |
它有三种写法:
1. 只规定原始图片开始剪切的位置,默认填充剩余宽高到画布上
drawImage(imageResource, dx, dy)
2. 从指定位置裁剪原始图片指定宽高,填充到画布上
drawImage(imageResource, dx, dy, dWidth, dHeight)
3. 从指定位置裁剪原始图片指定宽高,从指定位置开始显示到画布上指定宽高
drawImage(imageResource, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
这里我用到的是以上的第三种写法。
首先,在绘画图片之前,如果图片是网络资源(非本地资源)的话,就需要先用getSystemInfo获取到图片的本地路径和宽高。
<canvas canvas-id="canvas" style="width: {{canvasWidth}}px; height: {{canvasWidth}}px;"></canvas>
data: {
canvasWidth: null,
imgInfo: null
},
onLoad() {
let that = this;
// 获取系统信息,设置canvas宽高
wx.getSystemInfo({
success(res) {
that.setData({
canvasWidth: res.windowWidth
})
}
})
// 获取图片信息
wx.getImageInfo({
src: 'https://xxx.jpg',
success (res) {
that.setData({
imgInfo: res
})
// 制作画布
that.makeCanvas();
}
})
},
makeCanvas() {
var ctx = wx.createCanvasContext('canvas')
// 设置背景
ctx.setFillStyle('#ffffff')
ctx.fillRect(0, 0, this.data.canvasWidth, this.data.canvasWidth)
// canvas宽高
let cWidth = this.data.canvasWidth;
let cHeight = this.data.canvasWidth;
// 描绘图片
drawImage(this.data.imgInfo.path, this.data.imgInfo.width, this.data.imgInfo.height);
/**
* @function drawImage Canvas描绘图片
* @param {String} imgPath 图片路径
* @param {Number} imgWidth 图片宽度
* @param {Number} imgHeight 图片高度
* @author mossbaoo
*/
function drawImage(imgPath, imgWidth, imgHeight) {
let dWidth = cWidth/imgWidth; // canvas与图片的宽度比例
let dHeight = cHeight/imgHeight; // canvas与图片的高度比例
if (imgWidth > cWidth && imgHeight > cHeight || imgWidth < cWidth && imgHeight < cHeight) {
if (dWidth > dHeight) {
ctx.drawImage(imgPath, 0, (imgHeight - cHeight/dWidth)/2, imgWidth, cHeight/dWidth, 0, 0, cWidth, cHeight)
} else {
ctx.drawImage(imgPath, (imgWidth - cWidth/dHeight)/2, 0, cWidth/dHeight, imgHeight, 0, 0, cWidth, cHeight)
}
} else {
if (imgWidth < cWidth) {
ctx.drawImage(imgPath, 0, (imgHeight - cHeight/dWidth)/2, imgWidth, cHeight/dWidth, 0, 0, cWidth, cHeight)
} else {
ctx.drawImage(imgPath, (imgWidth - cWidth/dHeight)/2, 0, cWidth/dHeight, imgHeight, 0, 0, cWidth, cHeight)
}
}
}
ctx.draw()
}