context.drawImage(img,originXFrom,originYFrom,imgBeforeWidth,imgBeforeHeight,toCanvasFromX,toCanvasFromY,imgAfterWidth,imgAfterHeight)
参数介绍:
- img
:原图像
- originXFrom
:引用原图像时在原图像的横轴偏移位置
- originYFrom
:引用原图像时在原图像的纵轴偏移位置
- imgBeforeWidth
:原图像的width
- toCanvasFromX
:从canvas的横轴偏移位置开始画图
- 这里写imgAfterWidth
:压缩后图片width
2. canvas.toDataURL('image/type',quality)
参数介绍:
- type
:将要生成的图像类型,默认为png
,可指定为jpg
或者webp
,若指定的类型错误,则使用默认设置
- quality
:图像压缩质量,范围[0,1],数值越小,压缩比例越大
3. imageData = context.getImageData(xFrom,yFrom,xTo,yTo)
imageData的值中data为数组,将每个像素点转换为4个字节,分别表示rgba,a一般为255,a=255表示完全可见,a=0表示完全透明
4. context.putImageData(imageData,fromX,fromY)
参数介绍:
- imageData
:由getImageData
得到的值
- fromX
:从画布的偏移位置开始画
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<div id="img1">
<img data-src="123.jpg" src="" alt="left ear" id="i">
div>
<canvas id="canvasCopy">canvas>
<script type="text/javascript">
var ele = document.getElementById('i'),
url =ele.dataset.src,
afterWidth = 214,
afterHeight = 300,
quality = 0.3;
setImage(url,afterWidth,afterHeight,quality,ele);
function setImage(url,afterWidth,afterHeight,quality,ele) {
var image = new Image();
image.onload = function () {
var canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
beforeWidth = this.width,
beforeHeight = this.height,
dataurl = '';
canvas.width = afterWidth;
canvas.height = afterHeight;
context.drawImage(image,0, 0, beforeWidth, beforeHeight, 0, 0, afterWidth, afterHeight );
dataurl = canvas.toDataURL('image/webp',quality);
/*
* 以下是getImageData和putImageData的使用细节*/
var imagedata = context.getImageData(0,0,afterWidth,afterHeight);
console.log(imagedata)
var canvasCopy = document.getElementById('canvasCopy');
canvasCopy.width = afterWidth;
canvasCopy.height = afterHeight;
canvasCopy.getContext('2d').putImageData(imagedata,0,0);
ele.src = dataurl;
image.onload = null;
};
image.src = url;
}
script>
body>
html>