QQ2024410-17653
使用canvas对图片进行放大缩小,移动,旋转的操作
如果图片多或者其他滚动加载一类的可以明显提升性能,后续可以把视频也放进canvas播放
1. 鼠标点击到图片上面拖动的是图片
2. 鼠标点击到canvas空白的地方拖动的是canvas
3. 鼠标放到canvas空白的地方滚动是放大缩小canvas
4. 鼠标放到图片上滚动是放大缩小图片
5. 鼠标点击一张图片然后按esc是删除当前图片
6. 鼠标点击一张图可以控制旋转角度
<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>canvas</title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/3.3.4/vue.global.prod.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
canvas {
background-color: antiquewhite;
}
</style>
</head>
<body>
<div id="app">
<canvas ref="canvas"
:width="canvasWH.width * devicePixelRatio"
:height="canvasWH.height * devicePixelRatio"
@wheel="canvasWheel"
@mousedown="canvasMouseDown"
@mousemove="canvasMouseMove"
@mouseup="canvasMouseUp"
:style="{width: canvasStyleWH.width + 'px', height: canvasStyleWH.height + 'px'}"
>
</canvas>
<input type="file" @change="getPicture">
<div v-if="mouseDownPic">
<button @click="mouseDownPic.needRotate = !mouseDownPic.needRotate">修改当前可旋转状态</button>
当前图片是否可以旋转:{{ mouseDownPic.needRotate }} -- {{ mouseDownPic.rotate }}
<!-- 进度条 -->
<input type="range" @input="changeNowRange" min="0" max="360" value="0" step="1">
</div>
</div>
<script >
const { createApp, ref, reactive, onMounted } = Vue;
createApp({
setup() {
const canvas = ref();
const ctx = ref();
// 当前画布大小
const canvasWH = reactive({width: 600, height: 600});
// 当前画板大小
const canvasStyleWH = reactive({width: 600, height: 600 });
// 画布像素比
const devicePixelRatio = ref(1);
// 当前画布的偏移量
const canvasPYLT = reactive({left: 0, top: 0});
// 画布放大缩小的步长
const canvasTemp = ref(1);
// 鼠标按下
const mouseIsDown = ref(false);
const mouseDownXY = {x: 0, y: 0};
const nowClickImg = ref();
const mouseDownPic = ref();
// 当前传入的图片列表
const imgList = ref([]);
/** 在canvas上绘画图片 */
const getPicture = (e) => {
const files = e.target.files;
if(files.length){
const file = files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend=function(){
dataImg = reader.result;
let image = new Image();
image.src = dataImg;
image.onload = function (params) {
// 将图片放到canvas中间
let allW = canvasWH.width * devicePixelRatio.value;
let allH = canvasWH.height * devicePixelRatio.value;
let x = Math.floor((allW - image.width) / 2 - canvasPYLT.left);
let y = Math.floor((allH - image.height) / 2 - canvasPYLT.top);
// 图片的信息
imgList.value.unshift({image, width: image.width, height: image.height, x: x, y: y, needRotate: false, rotate: 0})
};
}
}
}
/** 将数组的某一项提取到数组第一项 */
const moveElementToFirst = (arr, target) => {
const index = arr.indexOf(target);
if (index !== -1) {
arr.splice(0, 0, ...arr.splice(index, 1));
}
return arr;
}
/** 判断点击是不是在当前图片范围内 */
const findClickedImage = (mouseX, mouseY) => {
const scaleW = canvasWH.width * devicePixelRatio.value / canvasStyleWH.width;
const scaleH = canvasWH.height * devicePixelRatio.value / canvasStyleWH.height;
for (const imageInfo of imgList.value) {
if(imageInfo.needRotate) {
// 如果当前的图片发生了旋转,需要计算一下当前的范围
const centerX = imageInfo.x + canvasPYLT.left + imageInfo.width / 2;
const centerY = imageInfo.y + canvasPYLT.top + imageInfo.height / 2;
const radians = imageInfo.rotate * Math.PI / 180; // 将角度转换为弧度
const rotationMatrix = [
Math.cos(radians), Math.sin(radians),
-Math.sin(radians), Math.cos(radians)
];
// 点击位置到长方形中心的向量
const V_click = [mouseX * scaleW - centerX, mouseY * scaleH - centerY];
const V_rotated = [
rotationMatrix[0] * V_click[0] + rotationMatrix[1] * V_click[1],
rotationMatrix[2] * V_click[0] + rotationMatrix[3] * V_click[1]
];
const halfWidth = imageInfo.width / 2;
const halfHeight = imageInfo.height / 2;
if( Math.abs(V_rotated[0]) <= halfWidth && Math.abs(V_rotated[1]) <= halfHeight ) {
return imageInfo;
}
} else {
if (
mouseX * scaleW >= imageInfo.x + canvasPYLT.left &&
mouseX * scaleW <= imageInfo.x + canvasPYLT.left + imageInfo.width &&
mouseY * scaleH >= imageInfo.y + canvasPYLT.top &&
mouseY * scaleH <= imageInfo.y + canvasPYLT.top + imageInfo.height
) {
return imageInfo;
}
}
}
return null; // 没有找到包含点击坐标的图片
}
/** 给canvas添加放大缩小功能 */
const canvasWheel = (e) => {
e.stopPropagation();
e.preventDefault();
nowClickImg.value = findClickedImage(e.offsetX, e.offsetY);
moveElementToFirst(imgList.value, nowClickImg.value); // 调整展示顺序
/** 判断是向上还是向下滚动 */
let isScrollTop = e.deltaY < 0 ? true : false;
let fuhao = isScrollTop ? 1 : -1;
if(nowClickImg.value) {
const scaleW = canvasWH.width * devicePixelRatio.value / canvasStyleWH.width;
const scaleH = canvasWH.height * devicePixelRatio.value / canvasStyleWH.height;
// 图片的宽高不是相同的,这里计算出来宽高比例,让图片放大缩小按照比例来
const imgScalc = nowClickImg.value.width / nowClickImg.value.height;
// 向上滚动的时候,放大图片,
nowClickImg.value.width += canvasTemp.value * fuhao * imgScalc;
nowClickImg.value.height += canvasTemp.value * fuhao;
// 计算当前左边和上边的百分比,计算的是图片的
const left = ((e.offsetX * scaleW - nowClickImg.value.x - canvasPYLT.left) / nowClickImg.value.width) * imgScalc;
const top = (e.offsetY * scaleH - nowClickImg.value.y - canvasPYLT.top) / nowClickImg.value.height;
// 然后根据当前鼠标在画布的位置进行偏移,让放大中心在鼠标位置
// 获取当前鼠标相对于画布的位置 offsetX offsetY
// 添加-1 是因为放大缩小是向相反位置移动
nowClickImg.value.x += left * canvasTemp.value * fuhao * -1;
nowClickImg.value.y += top * canvasTemp.value * fuhao * -1;
} else {
// 向上滚动的时候放大画布
// 放大画布
canvasWH.width += canvasTemp.value * fuhao / devicePixelRatio.value;
canvasWH.height += canvasTemp.value * fuhao / devicePixelRatio.value;
// 计算当前左边和上边的百分比
const left = e.offsetX / canvasStyleWH.width;
const top = e.offsetY / canvasStyleWH.height;
// 然后根据当前鼠标在画布的位置进行偏移,让放大中心在鼠标位置
// 获取当前鼠标相对于画布的位置 offsetX offsetY
canvasPYLT.left += left * canvasTemp.value * fuhao;
canvasPYLT.top += top * canvasTemp.value * fuhao;
}
// 操作完成之后把选中的图片去掉
nowClickImg.value = null;
}
/** canvas的鼠标按下 */
const canvasMouseDown = (e) => {
mouseIsDown.value = true;
mouseDownXY.x = e.offsetX;
mouseDownXY.y = e.offsetY;
nowClickImg.value = findClickedImage(e.offsetX, e.offsetY);
moveElementToFirst(imgList.value, nowClickImg.value); // 调整展示顺序
mouseDownPic.value = nowClickImg.value; // 当前点击的项,用于esc删除
}
/** canvas的鼠标抬起 */
const canvasMouseUp = (e) => {
mouseIsDown.value = false;
mouseDownXY.x = 0;
mouseDownXY.y = 0;
// 鼠标抬起的时候需要把图片像素设置成整数,避免模糊 wheel那里就不用了,避免移动的中心发生改变
// 如果感觉在移动的时候模糊,想要清晰,那就在移动的时候都移动到整数,但是这样会导致偏移,
// 所以需要在每次取整的时候把偏移量记下,等偏移量达到1的时候就加一
if(nowClickImg.value) {
nowClickImg.value.x = Math.floor(nowClickImg.value.x);
nowClickImg.value.y = Math.floor(nowClickImg.value.y);
nowClickImg.value = null;
}
canvasPYLT.left = Math.floor(canvasPYLT.left);
canvasPYLT.top = Math.floor(canvasPYLT.top);
}
/** canvas的鼠标移动 */
const canvasMouseMove = (e) => {
if(mouseIsDown.value) {
const scaleW = canvasWH.width * devicePixelRatio.value / canvasStyleWH.width;
const scaleH = canvasWH.height * devicePixelRatio.value / canvasStyleWH.height;
if(nowClickImg.value) {
// 让当前点击到的图片移动
nowClickImg.value.x += (e.offsetX - mouseDownXY.x) * scaleW;
nowClickImg.value.y += (e.offsetY - mouseDownXY.y) * scaleH;
} else {
// 让canvas画布移动
canvasPYLT.left += (e.offsetX - mouseDownXY.x) * scaleW;
canvasPYLT.top += (e.offsetY - mouseDownXY.y) * scaleH;
}
mouseDownXY.x = e.offsetX;
mouseDownXY.y = e.offsetY;
}
}
/** 使用requestAnimationFrame保证刷新频率 */
const drawImage = () => {
ctx.value.clearRect(0, 0, canvasWH.width * devicePixelRatio.value, canvasWH.height * devicePixelRatio.value);
// 保存当前状态
ctx.value.save();
// 平移坐标系
ctx.value.translate(canvasPYLT.left, canvasPYLT.top);
for(let i=imgList.value.length -1; i>=0; i--) {
let item = imgList.value[i];
if(item.needRotate) {
// 旋转图片 顺时针旋转
ctx.value.save();
ctx.value.translate(item.x + item.width / 2 , item.y + item.height / 2);
ctx.value.rotate(Math.PI / 180 * item.rotate);
ctx.value.drawImage(item.image, -item.width / 2, -item.height / 2, item.width, item.height);
// 恢复设置(恢复的步骤与修改的步骤向反)
ctx.value.rotate(-Math.PI / 180 * item.rotate);
ctx.value.translate(-(item.x + item.width / 2), -(item.y + item.height / 2));
ctx.value.restore();
} else {
// 向canvas添加图片
ctx.value.drawImage(item.image, item.x, item.y, item.width, item.height);
}
}
// 恢复之前保存的状态
ctx.value.restore();
requestAnimationFrame(drawImage);
};
// 监听按键按下,在按esc的时候删除对应的图片
const keydown = (e) => {
if (event.key === 'Escape' || event.keyCode === 27) {
e.stopPropagation();
e.preventDefault();
if(mouseDownPic.value) {
imgList.value.shift();
mouseDownPic.value = null;
}
}
}
// 当前图片的旋转角度
const changeNowRange = (e) => {
if(mouseDownPic.value) {
mouseDownPic.value.rotate = e.target.value;
}
}
onMounted(()=>{
ctx.value = canvas.value.getContext("2d");
// 获取设备像素比
let pixelRatio = window.devicePixelRatio || 1;
// 尝试获取 backingStorePixelRatio(非标准属性,可能不存在)
devicePixelRatio.value = pixelRatio * (ctx.value.backingStorePixelRatio || ctx.value.webkitBackingStorePixelRatio || ctx.value.msBackingStorePixelRatio || 1 ); // 若未找到,设为 1 作为默认值
requestAnimationFrame(drawImage);
document.removeEventListener("keydown", keydown);
document.addEventListener("keydown", keydown);
})
// 返回需要暴露给模板的数据和方法
return {
getPicture,
canvasWH,
devicePixelRatio,
canvasStyleWH,
canvas,
canvasWheel,
canvasMouseUp,
canvasMouseMove,
canvasMouseDown,
mouseDownPic,
changeNowRange
};
}
}).mount('#app');
</script>
</body>
</html>
一种优化的方法,理论上可以上传255 * 255 * 255张图片,并且能够更方便的确定点击的图片
想要做成一个图片裁剪组件,还没做完,后面再继续做
<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>canvas</title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/3.3.4/vue.global.prod.js"></script>
<script src="./canvasClass.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
canvas {
/* background-color: antiquewhite; */
}
</style>
</head>
<body>
<div id="app">
<canvas ref="canvas"></canvas>
<input type="file" @change="getPicture">
<div v-if="mouseDownPic">
<button @click="mouseDownPic.needRotate = !mouseDownPic.needRotate">修改当前可旋转状态</button>
<button @click="clipCanvasToImage">裁剪图片</button>
<button @click="changeNowFlipX">x翻转</button>
<button @click="changeNowFlipY">y翻转</button>
当前图片是否可以旋转:{{ mouseDownPic.needRotate }} -- {{ mouseDownPic.rotate }}
<!-- 进度条 -->
<input type="range" @input="changeNowRange" min="0" max="360" value="0" step="1">
</div>
<img :src="imgSrc" alt="">
</div>
<script >
const { createApp, ref, reactive, onMounted } = Vue;
createApp({
setup() {
/**
* 思路:
* 这是要做成一个canvas的功能组件,通过拿到传进来的canvas标签,来给这个canvas绑定方法
*/
// 获取canvas标签
const canvas = ref(null);
// 当前画布大小
const canvasWH = reactive({width: 208 * 10, height: 78 * 10});
// 当前画板大小
const canvasStyleWH = reactive({width: 600, height: 400});
// canvas的一些处理方法
const canvasFun = ref(null);
const mouseDownPic = ref();
const changeNowRange = (e) => {
const value = e.target.value;
if(mouseDownPic.value) {
mouseDownPic.value.rotate = value;
}
}
const changeNowFlipX = ()=>{
if(mouseDownPic.value) {
mouseDownPic.value.flipX =!mouseDownPic.value.flipX;
}
}
const changeNowFlipY = ()=>{
if(mouseDownPic.value) {
mouseDownPic.value.flipY =!mouseDownPic.value.flipY;
}
}
const imgSrc = ref('');
const clipCanvasToImage = ()=>{
imgSrc.value = canvasFun.value.clipCanvasToImage();
}
/** 在canvas上绘画图片 */
const getPicture = (e) => {
const files = e.target.files;
if(files.length){
const file = files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend=function(){
dataImg = reader.result;
let image = new Image();
image.src = dataImg;
image.onload = function (params) {
canvasFun.value.addImg(image)
};
}
}
}
onMounted(() => {
canvasFun.value = new Canvas({canvas: canvas.value,canvasWH, canvasStyleWH, mouseDownPic, canvasIsDoubleWH: true});
});
// 返回需要暴露给模板的数据和方法
return {
canvas,
getPicture,
mouseDownPic,
changeNowRange,
clipCanvasToImage,
imgSrc,
changeNowFlipX,
changeNowFlipY
};
}
}).mount('#app');
</script>
</body>
</html>
canvasClass.js
/**
* @description: 画布类
* @param {*} canavs: canvas对象
* @param {*} canvasWH: canvas的宽高
* @param {*} canvasStyleWH: canvas的样式宽高
* @param {*} mouseDownPic: 鼠标按下图片对象
* @param {*} canvasIsDoubleWH:画布是图片两倍宽高
*/
class Canvas {
constructor({canvas, canvasWH, canvasStyleWH, mouseDownPic, canvasIsDoubleWH}) {
// 获取canvas对象
this.canvas = canvas;
this.canvasWH = canvasWH;
this.canvasStyleWH = canvasStyleWH;
this.mouseDownPic = mouseDownPic;
this.canvasIsDoubleWH = canvasIsDoubleWH;
// 当前鼠标已经按下
this.mouseIsDown = false;
// 当前鼠标点击的坐标
this.mouseDownXY = {x: 0, y: 0};
// 当前传入的图片对象
this.imgListMap = new Map();
// 用于控制当前图片层级的数组
this.imgList = [];
// canvas的偏移量
this.canvasPYLT = {
left: this.canvas.offsetLeft,
top: this.canvas.offsetTop
};
// 步长
this.canvasTemp = {
value: 10
};
// 当前点击到的裁剪区域 边:左上、右上、右下、左下 上 下 左 右 中间部分
this.nowDownType = "";
this.canvasMask = {};
this.canvas2Image = {};
// 当前画布添加按键绑定事件
this.keydown();
// 当前点击的对象 rgb
this.clickObj = "";
// 获取canvas上下文
this.ctx = canvas.getContext("2d");
// 设备像素比
this.getDevicePixelRatio();
// 在一开始创建一个canvas,然后在这个canvas上绘画所有的图形,但是只绘画颜色,不用使用图片填充
// 在一开始创建一个canvas,然后把这个canvas当作主canvas的蒙版,用于绘制裁剪区域
this.getTempCanvas();
this.tempCanvasFun();
// 获取canvas信息
this.canvasResize();
// 给canvas添加滚动放大缩小事件
this.canvasWheel();
this.mousedown();
this.mousemove();
this.mouseup();
// 开始绘画 避免requestAnimationFrame修改this指向
this.draw = this.draw.bind(this);
this.draw();
// 存储当前删除的颜色
this.colorList = new Set();
// 存储当前已经获取到哪一个颜色
this.colorObj = {
r: 1,
g: 0,
b: 0
};
}
keydownFun(e){
if (event.key === "Escape" || event.keyCode === 27) {
e.stopPropagation();
e.preventDefault();
if(this.mouseDownPic.value) {
const deleteStr = this.imgList.shift();
this.imgListMap.delete(deleteStr);
this.mouseDownPic.value = null;
}
}
}
keydown(){
document.removeEventListener("keydown", this.keydownFun.bind(this));
document.addEventListener("keydown", this.keydownFun.bind(this));
}
// #region 绘画带角度的图形
drawRotate(ctx, item, isTemp){
// 需要先判断一下这个图片、图形在不在当前canvas可视区域内
ctx.save();
ctx.translate(item.x + item.width / 2, item.y + item.height / 2);
ctx.rotate(Math.PI / 180 * item.rotate);
if(isTemp) {
// 备份的canvas,只需要绘画一个填充颜色矩形的就可以
ctx.fillStyle = item.color;
ctx.fillRect(-item.width / 2, -item.height / 2, item.width, item.height);
} else {
if(item.flipX && item.flipY) {
// 翻转图片
this.ctx.scale(-1, -1);
} else if(item.flipX) {
// 翻转图片
this.ctx.scale(-1, 1);
} else if(item.flipY) {
// 翻转图片
this.ctx.scale(1, -1);
}
ctx.drawImage(item.image, -item.width / 2, -item.height / 2, item.width, item.height);
}
// 恢复设置(恢复的步骤与修改的步骤向反)
ctx.rotate(-Math.PI / 180 * item.rotate);
ctx.translate(-(item.x + item.width / 2), -(item.y + item.height / 2));
ctx.restore();
}
// 开始绘画
draw() {
this.ctx.clearRect(0, 0, this.canvasWH.width * this.devicePixelRatio.value, this.canvasWH.height * this.devicePixelRatio.value);
this.canvasTemp.ctx.clearRect(0, 0, this.canvasWH.width * this.devicePixelRatio.value, this.canvasWH.height * this.devicePixelRatio.value);
this.canvasMask.ctx.clearRect(0, 0, this.canvasWH.width * this.devicePixelRatio.value, this.canvasWH.height * this.devicePixelRatio.value);
this.canvasMaskAddModel();
// 保存当前状态
this.ctx.save();
this.canvasTemp.ctx.save();
// 平移坐标系
this.ctx.translate(this.canvasPYLT.left, this.canvasPYLT.top);
this.canvasTemp.ctx.translate(this.canvasPYLT.left, this.canvasPYLT.top);
// 倒着绘画
for(let i=this.imgList.length -1; i>=0; i--) {
let item = this.imgListMap.get(this.imgList[i]);
// 如果有旋转角度,就按照角度来旋转
if(item.needRotate) {
// 旋转图片 顺时针旋转
// 展示canvas
this.drawRotate(this.ctx, item);
// 备份canvas
this.drawRotate(this.canvasTemp.ctx, item, true);
} else {
if(item.flipX && item.flipY) {
// 翻转图片
this.ctx.save();
this.ctx.translate(item.x, item.y);
this.ctx.scale(-1, -1);
this.ctx.drawImage(item.image, -item.width, -item.height, item.width, item.height);
this.ctx.restore();
} else if(item.flipX) {
// 翻转图片
this.ctx.save();
this.ctx.translate(item.x, item.y);
this.ctx.scale(-1, 1);
this.ctx.drawImage(item.image, -item.width, 0, item.width, item.height);
this.ctx.restore();
} else if(item.flipY) {
// 翻转图片
this.ctx.save();
this.ctx.translate(item.x, item.y);
this.ctx.scale(1, -1);
this.ctx.drawImage(item.image, 0, -item.height, item.width, item.height);
this.ctx.restore();
} else {
// 向canvas添加图片
this.ctx.drawImage(item.image, item.x, item.y, item.width, item.height);
}
// 备份canvas添加矩形
this.canvasTemp.ctx.fillStyle = item.color;
this.canvasTemp.ctx.fillRect(item.x, item.y, item.width, item.height);
}
}
this.ctx.restore();
this.canvasTemp.ctx.restore();
requestAnimationFrame(this.draw);
}
// 用于获取一个不同颜色的函数
getColor(){
// 先判断colorList中有没有值
if(this.colorList.size > 0) {
// 获取第一个颜色
let color = this.colorList[0];
// 获取当前颜色
return `rgb(${color.r}, ${color.g}, ${color.b})`;
} else {
// 根据this.colorObj的值来获取一个颜色
let color = `rgb(${this.colorObj.r}, ${this.colorObj.g}, ${this.colorObj.b})`;
// 把this.colorObj的值加1 但是需要判断是否超出范围
this.colorObj.r += 1;
if(this.colorObj.r > 255) {
this.colorObj.r = 0;
this.colorObj.g += 1;
if(this.colorObj.g > 255) {
this.colorObj.g = 0;
this.colorObj.b += 1;
if(this.colorObj.b > 255) {
// 其实这里就是重复的颜色了,一般达不到这种情况
this.colorObj.b = 0;
// 000是画布颜色
this.colorObj.r = 1;
}
}
}
return color;
}
}
// 添加图片
addImg(image) {
if(this.canvasIsDoubleWH) {
// 根据图片大小设置画布大小,画布大小其中的宽或者高是图片的两倍
const width2 = image.width * 1.1;
const height2 = image.height * 1.1;
// 当前画板比例
const wh = this.canvasStyleWH.width / this.canvasStyleWH.height;
// 计算应该把画布的哪里放大
const scaleW = this.canvasStyleWH.width / width2;
const scaleH = this.canvasStyleWH.height / height2;
// 将大的那边占满画板,然后把小的那边根据画板宽高比例缩放
if(scaleW > scaleH) {
// 宽的比例大,说明是高的那边占满画板,这时候需要把宽的那边放大
this.canvasWH.height = height2;
this.canvasWH.width = height2 * wh;
} else {
// 高的比例大,说明是宽的那边占满画板,这时候需要把高的那边放大
this.canvasWH.width = width2;
this.canvasWH.height = width2 / wh;
}
this.canvasResize();
// 计算图片当前在画布的大小
let allW = this.canvasWH.width * this.devicePixelRatio.value;
let allH = this.canvasWH.height * this.devicePixelRatio.value;
let x = Math.floor((allW - image.width) / 2 - this.canvasPYLT.left);
let y = Math.floor((allH - image.height) / 2 - this.canvasPYLT.top);
// 根据当前图片的宽高和当前画布的宽高,设置当前裁剪的区域为图片的区域
this.canvasMask.styleRect = [
x / this.canvasWH.width * this.canvasStyleWH.width,
y / this.canvasWH.height * this.canvasStyleWH.height,
image.width / this.canvasWH.width * this.canvasStyleWH.width,
image.height / this.canvasWH.height * this.canvasStyleWH.height
];
}
// 将图片放到canvas中间
let allW = this.canvasWH.width * this.devicePixelRatio.value;
let allH = this.canvasWH.height * this.devicePixelRatio.value;
let x = Math.floor((allW - image.width) / 2 - this.canvasPYLT.left);
let y = Math.floor((allH - image.height) / 2 - this.canvasPYLT.top);
// 添加的图片放到第一项
// 添加的时候需要给当前图片添加一个颜色,用于区分当前是点击的哪个图片
let color = this.getColor();
const img = {image, width: image.width, height: image.height, x: x, y: y, needRotate: false, rotate: 0, color, flipX: false, flipY: false};
this.imgListMap.set(color, img);
this.imgList.unshift(color);
}
// #region 设备像素比
getDevicePixelRatio() {
// 设备像素比
this.devicePixelRatio = {
value: window.devicePixelRatio
};
let pixelRatio = window.devicePixelRatio || 1;
// 尝试获取 backingStorePixelRatio(非标准属性,可能不存在)
// 若未找到,设为 1 作为默认值
let backingStorePixelRatio = this.ctx.backingStorePixelRatio || this.ctx.webkitBackingStorePixelRatio || this.ctx.msBackingStorePixelRatio || 1 ;
this.devicePixelRatio.value = pixelRatio * backingStorePixelRatio;
}
// 获取canvas基本信息
canvasResize() {
this.canvas.width = this.canvasWH.width * this.devicePixelRatio.value;
this.canvas.height = this.canvasWH.height * this.devicePixelRatio.value;
this.canvas.style.width = this.canvasStyleWH.width + "px";
this.canvas.style.height = this.canvasStyleWH.height + "px";
this.tempCanvasFun();
}
// #region 获取当前点击图片
getMoveColor(e){
const scaleW = this.canvasWH.width * this.devicePixelRatio.value / this.canvasStyleWH.width;
const scaleH = this.canvasWH.height * this.devicePixelRatio.value / this.canvasStyleWH.height;
// 获取点击位置的颜色
const color = this.canvasTemp.ctx.getImageData(e.offsetX * scaleW, e.offsetY * scaleH, 1, 1).data;
// 将颜色值转换为RGB格式
if(color[0] == color[1] == color[2] == 0) {
this.clickObj = "";
} else {
this.clickObj = `rgb(${color[0]}, ${color[1]}, ${color[2]})`;
// 将点击的图片移动到最上面
this.moveElementToFirst(this.imgList, this.clickObj);
this.mouseDownPic.value = this.imgListMap.get(this.clickObj);
}
}
// #region 鼠标滚动事件
// 添加滚动放大缩小事件
canvasWheel() {
this.canvasMask.canvas.addEventListener("wheel", this.throttle((e) => {
// 这里不能每次都触发,要加一个节流
e.stopPropagation();
e.preventDefault();
// 获取当前点击的对象
this.getMoveColor(e);
/** 判断是向上还是向下滚动 */
let isScrollTop = e.deltaY < 0 ? true : false;
let fuhao = isScrollTop ? 1 : -1;
if(this.clickObj){
const nowClickImg = this.imgListMap.get(this.clickObj);
const scaleW = this.canvasWH.width * this.devicePixelRatio.value / this.canvasStyleWH.width;
const scaleH = this.canvasWH.height * this.devicePixelRatio.value / this.canvasStyleWH.height;
// 图片的宽高不是相同的,这里计算出来宽高比例,让图片放大缩小按照比例来
const imgScalc = nowClickImg.width / nowClickImg.height;
// 向上滚动的时候,放大图片,
nowClickImg.width += this.canvasTemp.value * fuhao * imgScalc;
nowClickImg.height += this.canvasTemp.value * fuhao;
// 计算当前左边和上边的百分比,计算的是图片的
const left = ((e.offsetX * scaleW - nowClickImg.x - this.canvasPYLT.left) / nowClickImg.width) * imgScalc;
const top = (e.offsetY * scaleH - nowClickImg.y - this.canvasPYLT.top) / nowClickImg.height;
// 然后根据当前鼠标在画布的位置进行偏移,让放大中心在鼠标位置
// 获取当前鼠标相对于画布的位置 offsetX offsetY
// 添加-1 是因为放大缩小是向相反位置移动
nowClickImg.x += left * this.canvasTemp.value * fuhao * -1;
nowClickImg.y += top * this.canvasTemp.value * fuhao * -1;
} else {
// 向上滚动的时候放大画布
// 放大画布
this.canvasWH.width += this.canvasTemp.value * fuhao / this.devicePixelRatio.value;
this.canvasWH.height += this.canvasTemp.value * fuhao / this.devicePixelRatio.value;
// 计算当前左边和上边的百分比
const left = e.offsetX / this.canvasStyleWH.width;
const top = e.offsetY / this.canvasStyleWH.height;
// 然后根据当前鼠标在画布的位置进行偏移,让放大中心在鼠标位置
// 获取当前鼠标相对于画布的位置 offsetX offsetY
this.canvasPYLT.left += left * this.canvasTemp.value * fuhao;
this.canvasPYLT.top += top * this.canvasTemp.value * fuhao;
}
this.clickObj = "";
this.canvasResize();
}, 18, {leading: true, trailing: true}));
}
// #region 添加鼠标按下事件
mousedown() {
this.canvasMask.canvas.addEventListener("mousedown", (e) => {
e.stopPropagation();
e.preventDefault();
this.mouseIsDown = true;
this.mouseDownXY.x = e.offsetX;
this.mouseDownXY.y = e.offsetY;
// 获取当前点击的对象
this.getMoveColor(e);
});
}
// #region 鼠标canvas上抬起事件
mouseUpCanvas(e) {
e.stopPropagation();
e.preventDefault();
this.mouseIsDown = false;
this.mouseDownXY.x = 0;
this.mouseDownXY.y = 0;
if(this.clickObj) {
this.imgListMap.get(this.clickObj).x = Math.floor(this.imgListMap.get(this.clickObj).x);
this.imgListMap.get(this.clickObj).y = Math.floor(this.imgListMap.get(this.clickObj).y);
this.clickObj = "";
}
// 鼠标抬起的时候需要把图片像素设置成整数,避免模糊 wheel那里就不用了,避免移动的中心发生改变
// 如果感觉在移动的时候模糊,想要清晰,那就在移动的时候都移动到整数,但是这样会导致偏移,
// 所以需要在每次取整的时候把偏移量记下,等偏移量达到1的时候就加一
this.canvasPYLT.left = Math.floor(this.canvasPYLT.left);
this.canvasPYLT.top = Math.floor(this.canvasPYLT.top);
// 鼠标抬起的时候,需要把裁剪区域修改一下,避免右下角拖动到了左上角的左边或者上边
if(this.canvasMask.styleRect[2] < 0) {
this.canvasMask.styleRect[0] += this.canvasMask.styleRect[2];
this.canvasMask.styleRect[2] = -this.canvasMask.styleRect[2];
}
if(this.canvasMask.styleRect[3] < 0) {
this.canvasMask.styleRect[1] += this.canvasMask.styleRect[3];
this.canvasMask.styleRect[3] = -this.canvasMask.styleRect[3];
}
}
// #region 添加鼠标抬起事件
mouseup() {
this.canvasMask.canvas.addEventListener("mouseup", (e) => {
this.mouseUpCanvas(e);
});
document.addEventListener("mouseup", (e) => {
this.mouseUpCanvas(e);
});
}
// #region 鼠标canvas上移动的事件
canvasMouseMoveFun(e) {
if(this.mouseIsDown) {
if(this.nowDownType == "noClipArea") {
const scaleW = this.canvasWH.width * this.devicePixelRatio.value / this.canvasStyleWH.width;
const scaleH = this.canvasWH.height * this.devicePixelRatio.value / this.canvasStyleWH.height;
if(this.imgListMap.has(this.clickObj)) {
// 让当前点击到的图片移动
this.imgListMap.get(this.clickObj).x += (e.offsetX - this.mouseDownXY.x) * scaleW;
this.imgListMap.get(this.clickObj).y += (e.offsetY - this.mouseDownXY.y) * scaleH;
} else {
// 让canvas画布移动
this.canvasPYLT.left += (e.offsetX - this.mouseDownXY.x) * scaleW;
this.canvasPYLT.top += (e.offsetY - this.mouseDownXY.y) * scaleH;
}
this.mouseDownXY.x = e.offsetX;
this.mouseDownXY.y = e.offsetY;
} else {
if (this.nowDownType == "center") {
// 裁剪区域位置移动
const x = this.canvasMask.styleRect[0] + (e.offsetX - this.mouseDownXY.x);
const y = this.canvasMask.styleRect[1] + (e.offsetY - this.mouseDownXY.y);
if(x < 0) {
this.canvasMask.styleRect[0] = 0;
} else if(x + this.canvasMask.styleRect[2] > this.canvasStyleWH.width) {
console.log("不需要处理");
// this.canvasMask.styleRect[0] = this.canvasStyleWH.width - this.canvasMask.styleRect[2];
} else {
this.canvasMask.styleRect[0] = x;
}
if(y < 0) {
this.canvasMask.styleRect[1] = 0;
} else if(y + this.canvasMask.styleRect[3] > this.canvasStyleWH.height) {
console.log("不需要处理");
// this.canvasMask.styleRect[1] = this.canvasStyleWH.height - this.canvasMask.styleRect[3];
} else {
this.canvasMask.styleRect[1] = y;
}
this.canvasMask.canvas.style.cursor = "grabbing";
} else if (this.nowDownType == "right") {
// 右边裁剪区域位置移动
this.canvasMask.styleRect[2] += (e.offsetX - this.mouseDownXY.x);
this.canvasMask.canvas.style.cursor = "ew-resize";
} else if (this.nowDownType == "bottom") {
// 下边裁剪区域位置移动
this.canvasMask.styleRect[3] += (e.offsetY - this.mouseDownXY.y);
this.canvasMask.canvas.style.cursor = "ns-resize";
} else if (this.nowDownType == "left") {
// 左边裁剪区域位置移动
this.canvasMask.styleRect[0] += (e.offsetX - this.mouseDownXY.x);
this.canvasMask.styleRect[2] -= (e.offsetX - this.mouseDownXY.x);
this.canvasMask.canvas.style.cursor = "ew-resize";
} else if (this.nowDownType == "top") {
// 上边裁剪区域位置移动
this.canvasMask.styleRect[1] += (e.offsetY - this.mouseDownXY.y);
this.canvasMask.styleRect[3] -= (e.offsetY - this.mouseDownXY.y);
this.canvasMask.canvas.style.cursor = "ns-resize";
} else if(this.nowDownType == "rightTop") {
// 右上角裁剪区域位置移动
this.canvasMask.styleRect[1] += (e.offsetY - this.mouseDownXY.y);
this.canvasMask.styleRect[3] -= (e.offsetY - this.mouseDownXY.y);
this.canvasMask.styleRect[2] += (e.offsetX - this.mouseDownXY.x);
this.canvasMask.canvas.style.cursor = "nesw-resize";
} else if(this.nowDownType == "rightBottom") {
// 右下角裁剪区域位置移动
this.canvasMask.styleRect[2] += (e.offsetX - this.mouseDownXY.x);
this.canvasMask.styleRect[3] += (e.offsetY - this.mouseDownXY.y);
this.canvasMask.canvas.style.cursor = "nwse-resize";
} else if(this.nowDownType == "leftTop") {
// 左上角裁剪区域位置移动
this.canvasMask.styleRect[0] += (e.offsetX - this.mouseDownXY.x);
this.canvasMask.styleRect[1] += (e.offsetY - this.mouseDownXY.y);
this.canvasMask.styleRect[2] -= (e.offsetX - this.mouseDownXY.x);
this.canvasMask.styleRect[3] -= (e.offsetY - this.mouseDownXY.y);
this.canvasMask.canvas.style.cursor = "nwse-resize";
} else if(this.nowDownType == "leftBottom") {
// 左下角裁剪区域位置移动
this.canvasMask.styleRect[2] -= (e.offsetX - this.mouseDownXY.x);
this.canvasMask.styleRect[3] += (e.offsetY - this.mouseDownXY.y);
this.canvasMask.styleRect[0] += (e.offsetX - this.mouseDownXY.x);
this.canvasMask.canvas.style.cursor = "nesw-resize";
}
this.mouseDownXY.x = e.offsetX;
this.mouseDownXY.y = e.offsetY;
}
} else {
// 判断当前鼠标移动的位置是否是在裁剪区域的各个部分
this.nowDownType = this.getNowDownType(e);
}
}
// #region 添加鼠标移动事件
mousemove() {
// 鼠标在canvas上移动时让裁剪区域跟随鼠标移动
this.canvasMask.canvas.addEventListener("mousemove", this.throttle((e)=>{
e.stopPropagation();
e.preventDefault();
this.canvasMouseMoveFun(e);
}, 18, {leading: true, trailing: true}));
// 鼠标在canvas外移动时让裁剪区域跟随鼠标移动
document.addEventListener("mousemove", this.throttle((e)=>{
const canvasRect = this.canvas.getBoundingClientRect();
// 判断当前鼠标是否在画布外面
if(e.clientX < canvasRect.left || e.clientX > canvasRect.right || e.clientY < canvasRect.top || e.clientY > canvasRect.bottom) {
// 鼠标在canvas外移动时让裁剪区域跟随鼠标移动
if(this.mouseIsDown) {
e.stopPropagation();
e.preventDefault();
// 获取当前画布的位置
// 获取当前鼠标的位置
let mouseX = e.clientX - canvasRect.left;
let mouseY = e.clientY - canvasRect.top;
if(mouseX < canvasRect.left) {
mouseX = canvasRect.left;
} else if(mouseX > canvasRect.right) {
mouseX = canvasRect.right;
}
if(mouseY < canvasRect.top) {
mouseY = canvasRect.top;
} else if(mouseY > canvasRect.bottom) {
mouseY = canvasRect.bottom;
}
this.canvasMouseMoveFun({offsetX: mouseX, offsetY: mouseY});
}
}
}, 18, {leading: true, trailing: true}));
}
/** 将数组的某一项提取到数组第一项 */
moveElementToFirst(arr, target) {
const index = arr.indexOf(target);
if (index !== -1) {
arr.splice(0, 0, ...arr.splice(index, 1));
}
return arr;
}
getTempCanvas(){
// 备份的canvas,只需要绘画一个填充颜色矩形的就可以
this.canvasTemp.canvas = document.createElement("canvas");
this.canvasTemp.ctx = this.canvasTemp.canvas.getContext("2d");
// 用于蒙版的canvas
this.canvasMask.canvas = document.createElement("canvas");
this.canvasMask.ctx = this.canvasMask.canvas.getContext("2d");
// 用于裁剪的canvas
this.canvas2Image.canvas = document.createElement("canvas");
this.canvas2Image.ctx = this.canvas2Image.canvas.getContext("2d");
// 设置传进来的canvas画布是相对定位
this.canvas.style.position = "relative";
// 灰白相间的方块
// this.canvas.style.backgroundImage = `linear-gradient( 45deg, rgba(0, 0, 0, 0.5) 25%, transparent 0, transparent 75%, rgba(0, 0, 0, 0.5) 0 ),
// linear-gradient(135deg, rgba(0, 0, 0, 0.5) 25%, transparent 0, transparent 75%, rgba(0, 0, 0, 0.5) 0)`;
// this.canvas.style.backgroundSize = "30px 30px";
// // this.canvas.style.backgroundRepeat = "no-repeat";
// this.canvas.style.backgroundColor = "#eee";
// 设置蒙版位置
this.canvasMask.canvas.width = this.canvas.width;
this.canvasMask.canvas.height = this.canvas.height;
this.canvasMask.canvas.style.position = "absolute"; // 绝对定位
this.canvasMask.canvas.style.top = this.canvas.offsetTop + "px";
this.canvasMask.canvas.style.left = this.canvas.offsetLeft + "px";
this.canvasMask.canvas.style.zIndex = "1"; // 确保覆盖层在最上层
this.canvasMask.canvas.style.backgroundColor = "transparent"; // 蒙版层背景色
// 添上蒙版层
this.canvas.parentNode.appendChild(this.canvasMask.canvas);
}
tempCanvasFun(){
// 备份的canvas,只需要绘画一个填充颜色矩形的就可以
this.canvasTemp.canvas.width = this.canvasWH.width * this.devicePixelRatio.value;
this.canvasTemp.canvas.height = this.canvasWH.height * this.devicePixelRatio.value;
this.canvasTemp.canvas.style.width = this.canvasStyleWH.width + "px";
this.canvasTemp.canvas.style.height = this.canvasStyleWH.height + "px";
// 用于裁剪的canvas
this.canvasMask.canvas.width = this.canvasWH.width * this.devicePixelRatio.value;
this.canvasMask.canvas.height = this.canvasWH.height * this.devicePixelRatio.value;
this.canvasMask.canvas.style.width = this.canvasStyleWH.width + "px";
this.canvasMask.canvas.style.height = this.canvasStyleWH.height + "px";
}
// 当前图片的旋转角度
changeNowRange(e){
if(this.mouseDownPic.value) {
this.mouseDownPic.value.rotate = e.target.value;
}
}
// 图片的翻转
changeNowFlipX(e){
if(this.mouseDownPic.value) {
this.mouseDownPic.value.flipX = !this.mouseDownPic.value.flipX;
}
}
changeNowFlipY(e){
if(this.mouseDownPic.value) {
this.mouseDownPic.value.flipY = !this.mouseDownPic.value.flipY;
}
}
// #region model Canvas
canvasMaskAddModel() {
// 绘制蒙版层
this.canvasMask.ctx.rect(0, 0, this.canvasMask.canvas.width, this.canvasMask.canvas.height);
// this.canvasMask.ctx.fillStyle = "rgba(0,0,0,0.3)";
// this.canvasMask.ctx.fill();
// 绘制裁剪区域 需要保存当前裁剪窗口的画板大小
// 然后下次绘画的时候,根据画板大小计算新的画布大小进行绘制
if(this.canvasMask.clipRect) {
this.canvasMask.clipRect = [
this.canvasMask.canvas.width * this.canvasMask.styleRect[0] / this.canvasStyleWH.width,
this.canvasMask.canvas.height * this.canvasMask.styleRect[1] / this.canvasStyleWH.height,
this.canvasMask.canvas.width * this.canvasMask.styleRect[2] / this.canvasStyleWH.width,
this.canvasMask.canvas.height * this.canvasMask.styleRect[3] / this.canvasStyleWH.height
];
} else {
this.canvasMask.styleRect = [this.canvasStyleWH.width/4, this.canvasStyleWH.height/4, this.canvasStyleWH.width/2, this.canvasStyleWH.height/2];
// 根据样式大小的裁剪区域,计算出裁剪区域的大小
this.canvasMask.clipRect = [
this.canvasMask.canvas.width * this.canvasMask.styleRect[0] / this.canvasStyleWH.width,
this.canvasMask.canvas.height * this.canvasMask.styleRect[1] / this.canvasStyleWH.height,
this.canvasMask.canvas.width * this.canvasMask.styleRect[2] / this.canvasStyleWH.width,
this.canvasMask.canvas.height * this.canvasMask.styleRect[3] / this.canvasStyleWH.height
];
}
// 单独处理图片上才能有蒙版显示
this.canvasMask.ctx.fillStyle = "rgba(0,0,0,0.4)";
this.imgListMap.forEach((value, key) => {
// 绘制蒙版
this.canvasMask.ctx.fillRect(value.x, value.y, value.width, value.height);
});
this.canvasMask.ctx.clearRect(this.canvasMask.clipRect[0], this.canvasMask.clipRect[1], this.canvasMask.clipRect[2], this.canvasMask.clipRect[3]);
this.getLine({
ctx2: this.canvasMask.ctx,
size: {width: this.canvasMask.clipRect[2], height: this.canvasMask.clipRect[3]},
canvasModalXY: {x: this.canvasMask.clipRect[0], y: this.canvasMask.clipRect[1]}
});
}
// #region 计算当前鼠标在哪个区域
getNowDownType(e) {
// 区域分为10个:左上角,左边,上边,右上角,右边,下边,左下角,右下角,中间 外部其他区域
const scaleW = this.canvasWH.width * this.devicePixelRatio.value / this.canvasStyleWH.width;
const scaleH = this.canvasWH.height * this.devicePixelRatio.value / this.canvasStyleWH.height;
// 获取鼠标所在画布位置
const mouseXY = {
X: e.offsetX * scaleW,
Y: e.offsetY * scaleH
};
const canvasModalSize = {
X: this.canvasMask.canvas.width * this.canvasMask.styleRect[0] / this.canvasStyleWH.width,
Y: this.canvasMask.canvas.height * this.canvasMask.styleRect[1] / this.canvasStyleWH.height,
width: this.canvasMask.canvas.width * this.canvasMask.styleRect[2] / this.canvasStyleWH.width,
height: this.canvasMask.canvas.height * this.canvasMask.styleRect[3] / this.canvasStyleWH.height
};
const padding = 20; // 鼠标偏移范围
const width = 10; // 鼠标宽度
if (mouseXY.X < canvasModalSize.X - width || mouseXY.X > canvasModalSize.X + canvasModalSize.width - width + padding) {
this.canvasMask.canvas.style.cursor = "move";
return "noClipArea";
} else if (mouseXY.X < canvasModalSize.X - width + padding) {
if (mouseXY.Y < canvasModalSize.Y - width || mouseXY.Y > canvasModalSize.Y + canvasModalSize.height - width + padding) {
this.canvasMask.canvas.style.cursor = "move";
return "noClipArea";
} else if (mouseXY.Y < canvasModalSize.Y - width + padding) {
this.canvasMask.canvas.style.cursor = "nwse-resize";
return "leftTop";
} else if (mouseXY.Y < canvasModalSize.Y + canvasModalSize.height - width) {
this.canvasMask.canvas.style.cursor = "ew-resize";
return "left";
} else if (mouseXY.Y < canvasModalSize.Y + canvasModalSize.height - width + padding) {
this.canvasMask.canvas.style.cursor = "nesw-resize";
return "leftBottom";
}
} else if (mouseXY.X < canvasModalSize.X + canvasModalSize.width - width) {
if (mouseXY.Y < canvasModalSize.Y - width || mouseXY.Y > canvasModalSize.Y + canvasModalSize.height - width + padding) {
this.canvasMask.canvas.style.cursor = "move";
return "noClipArea";
} else if (mouseXY.Y < canvasModalSize.Y - width + padding) {
this.canvasMask.canvas.style.cursor = "ns-resize";
return "top";
} else if (mouseXY.Y < canvasModalSize.Y + canvasModalSize.height - width) {
this.canvasMask.canvas.style.cursor = "grab";
return "center";
} else if (mouseXY.Y < canvasModalSize.Y + canvasModalSize.height - width + padding) {
this.canvasMask.canvas.style.cursor = "ns-resize";
return "bottom";
}
} else if (mouseXY.X < canvasModalSize.X + canvasModalSize.width - width + padding) {
if (mouseXY.Y < canvasModalSize.Y - width || mouseXY.Y > canvasModalSize.Y + canvasModalSize.height - width + padding) {
this.canvasMask.canvas.style.cursor = "move";
return "noClipArea";
} else if (mouseXY.Y < canvasModalSize.Y - width + padding) {
this.canvasMask.canvas.style.cursor = "nesw-resize";
return "rightTop";
} else if (mouseXY.Y < canvasModalSize.Y + canvasModalSize.height - width) {
this.canvasMask.canvas.style.cursor = "ew-resize";
return "right";
} else if (mouseXY.Y < canvasModalSize.Y + canvasModalSize.height - width + padding) {
this.canvasMask.canvas.style.cursor = "nwse-resize";
return "rightBottom";
}
}
return "noClipArea";
}
// #region model画线
/**
* @param {*} data 要执行的函数 ctx2 画布 size裁剪宽高 canvasModalXY 画线起始位置 x,y坐标
* @returns
*/
getLine(data) {
const { ctx2, size, canvasModalXY } = data;
/** 给空白处画上虚线 */
// 1.将空白处横向竖向分成三部分
const lineNumber = 3;
// 基础线宽,根据宽高大的那边来定
let baseLineWidth = 1;
if (this.canvasWH.width > this.canvasWH.height) {
baseLineWidth = this.canvasWH.width / 700;
} else {
baseLineWidth = this.canvasWH.height / 700;
}
// 当前画线的比率,有些图片像素高,需要更粗的线段 向上取整
const lineRatio = this.canvasWH.width / this.canvasWH.height;
// 这里处理横纵两条线显示的一样宽
let lineRatioX = 1; // 横线比率
let lineRatioY = 1; // 竖线比率
let lineDashX = 10; // 横线间隔
let lineDashY = 10; // 竖线间隔
if (lineRatio >=1) {
// 宽度大,高度小,说明横线更细,竖线需要更粗
lineRatioX = 1;
lineRatioY = lineRatio;
// 要想看起来一样,需要处理下横线竖线间隔
lineDashX = 10 * lineRatio;
lineDashY = 10;
} else {
// 宽度小,高度大,说明竖线更细,横线需要更粗
lineRatioX = 1 / lineRatio;
lineRatioY = 1;
// 要想看起来一样,需要处理下横线竖线间隔
lineDashX = 10;
lineDashY = 10 * lineRatio;
}
/** 每一行的高度、宽度 */
const xLineSpace = size.height / lineNumber;
const yLineSpace = size.width / lineNumber;
/** 划线起始位置,减去0.5画的更清楚 */
const yBeginLine = canvasModalXY.x - 0.5;
const xBeginLine = canvasModalXY.y - 0.5;
// y轴
for (let i = 0; i < lineNumber + 1; i++) {
// 画y轴
ctx2.beginPath();
ctx2.lineWidth = 1 * lineRatioY * baseLineWidth;
ctx2.setLineDash([lineDashY * baseLineWidth, lineDashY * 0.4 * baseLineWidth]);
ctx2.moveTo(yBeginLine + i * yLineSpace - 0.5, xBeginLine);
ctx2.lineTo(yBeginLine + i * yLineSpace - 0.5, xBeginLine + size.height);
ctx2.strokeStyle = "#409EFF";
ctx2.stroke();
// 画x轴
ctx2.beginPath();
ctx2.lineWidth = 1 * lineRatioX * baseLineWidth;
ctx2.setLineDash([lineDashX * baseLineWidth, lineDashX * 0.4 * baseLineWidth]);
ctx2.moveTo(yBeginLine, xBeginLine + i * xLineSpace - 0.5);
ctx2.lineTo(yBeginLine + size.width, xBeginLine + i * xLineSpace - 0.5);
ctx2.strokeStyle = "#409EFF";
ctx2.stroke();
}
// 在四个角画对号 左上 右上 右下 左下
const pointMove = 5; // 距离四个角的xy距离
const lineWidth = 30; // 线长
const strokeArr = [
{
moveTo: { X: yBeginLine - pointMove + lineWidth, Y: xBeginLine - pointMove },
lineToOne: { X: yBeginLine - pointMove, Y: xBeginLine - pointMove },
lineToTwo: { X: yBeginLine - pointMove, Y: xBeginLine - pointMove + lineWidth }
},
{
moveTo: {
X: yBeginLine + size.width + pointMove - lineWidth,
Y: xBeginLine - pointMove
},
lineToOne: { X: yBeginLine + size.width + pointMove, Y: xBeginLine - pointMove },
lineToTwo: {
X: yBeginLine + size.width + pointMove,
Y: xBeginLine - pointMove + lineWidth
}
},
{
moveTo: {
X: yBeginLine + size.width + pointMove - lineWidth,
Y: xBeginLine + lineNumber * xLineSpace + pointMove
},
lineToOne: {
X: yBeginLine + size.width + pointMove,
Y: xBeginLine + lineNumber * xLineSpace + pointMove
},
lineToTwo: {
X: yBeginLine + size.width + pointMove,
Y: xBeginLine + lineNumber * xLineSpace + pointMove - lineWidth
}
},
{
moveTo: {
X: yBeginLine - pointMove,
Y: xBeginLine + size.height + pointMove - lineWidth
},
lineToOne: { X: yBeginLine - pointMove, Y: xBeginLine + size.height + pointMove },
lineToTwo: {
X: yBeginLine - pointMove + lineWidth,
Y: xBeginLine + size.height + pointMove
}
}
];
strokeArr.forEach((item) => {
ctx2.beginPath();
ctx2.lineWidth = 4;
ctx2.setLineDash([0, 0]);
ctx2.moveTo(item.moveTo.X, item.moveTo.Y);
ctx2.lineTo(item.lineToOne.X, item.lineToOne.Y);
ctx2.lineTo(item.lineToTwo.X, item.lineToTwo.Y);
ctx2.strokeStyle = "#999";
ctx2.stroke();
});
}
// #region 图片裁剪
clipCanvasToImage(){
const image3 = new Image();
const canvasModalSize = {
X: this.canvasMask.canvas.width * this.canvasMask.styleRect[0] / this.canvasStyleWH.width,
Y: this.canvasMask.canvas.height * this.canvasMask.styleRect[1] / this.canvasStyleWH.height,
width: this.canvasMask.canvas.width * this.canvasMask.styleRect[2] / this.canvasStyleWH.width,
height: this.canvasMask.canvas.height * this.canvasMask.styleRect[3] / this.canvasStyleWH.height
};
const image1Data = this.ctx.getImageData(canvasModalSize.X, canvasModalSize.Y, canvasModalSize.width, canvasModalSize.height);
this.canvas2Image.canvas.height = canvasModalSize.height;
this.canvas2Image.canvas.width = canvasModalSize.width;
this.canvas2Image.ctx.clearRect(0, 0, this.canvas2Image.width, this.canvas2Image.height);
this.canvas2Image.ctx.putImageData(image1Data, 0, 0);
image3.src = this.canvas2Image.canvas.toDataURL("image/png");
return image3.src;
}
// #region 节流函数
/**
* @param {*} fn 要执行的函数
* @param {*} interval 时间间隔
* @param {*} options 可选参数: leading第一次是否执行, trailing 最后一次是否执行
* @returns
*/
throttle(fn, interval, options = {leading: true, trailing: false,}) {
const { leading, trailing } = options;
// 1.记录上一次的开始时间
let lastTime = 0;
let timer = null;
// 2.事件触发时, 真正执行的函数
const _throttle = function (...args) {
// 2.1.获取当前事件触发时的时间
const nowTime = new Date().getTime();
//当lastTime为0时且第一次不执行
if (!lastTime && !leading) lastTime = nowTime;
// 2.2.使用当前触发的时间和之前的时间间隔以及上一次开始的时间, 计算出还剩余多长事件需要去触发函数
const remainTime = interval - (nowTime - lastTime);
if (remainTime <= 0) {
if (timer) {
//执行函数时,需要取消定时器
clearTimeout(timer);
timer = null;
}
// 2.3.真正触发函数
fn.apply(this, args);
// 2.4.保留上次触发的时间
lastTime = nowTime;
return;
}
//当最后一次需要执行且没有定时器时,只需要创建一个定时器,还有多久触发由remainTime决定
if (trailing && !timer) {
timer = setTimeout(() => {
fn.apply(this, args);
timer = null; //执行后重置
lastTime = !leading ? 0 : new Date().getTime(); //第一次不执行时为0,第一次执行时为定时器执行时的时间
}, remainTime);
}
};
return _throttle;
}
}
// export default Canvas;
270




被折叠的 条评论
为什么被折叠?



