- originUrl 图片原地址
- cWidth 生成图片的宽度
- cHeight 生成图片的高度
- top 第一条切割线距离原图片顶部的距离
- bottom 第二条切割线距离原图片底部的距离
- left 第三条切割线距离原图片左侧的距离
- right 第四条切割线距离原图片右侧的距离
切割
效果图
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>原图片</div>
<img src="./img/3.png" />
<div>切割后图片</div>
<img class="myImg" />
<script type="module">
import './index.js'
</script>
</body>
</html>
index.js
import drawImage from "./squared.js";
const myImg = document.querySelector(".myImg");
drawImage("/img/3.png", 1000, 100, 10, 10, 10, 10).then((res) => {
myImg.src = res;
});
export {};
squared.js
const handleImg = (ctx, w, h, img, cw, ch, top, bottom, right, left) => {
ctx.drawImage(img, 0, 0, left, top, 0, 0, left, top);
ctx.drawImage(
img,
left,
0,
w - right - left,
top,
left,
0,
cw - right - left,
top
);
ctx.drawImage(img, w - right, 0, right, top, cw - right, 0, right, top);
ctx.drawImage(
img,
0,
top,
left,
h - top - bottom,
0,
top,
left,
ch - bottom - top
);
ctx.drawImage(
img,
left,
top,
w - right - left,
h - top - bottom,
left,
top,
cw - left - right,
ch - top - bottom
);
ctx.drawImage(
img,
w - right,
top,
right,
h - top - bottom,
cw - right,
top,
right,
ch - top - bottom
);
ctx.drawImage(img, 0, h - bottom, left, bottom, 0, ch - bottom, left, bottom);
ctx.drawImage(
img,
left,
h - bottom,
w - right - left,
bottom,
left,
ch - bottom,
cw - left - right,
bottom
);
ctx.drawImage(
img,
w - right,
h - bottom,
right,
bottom,
cw - right,
ch - bottom,
right,
bottom
);
};
const drawImage = (originUrl, cWidth, cHeight, top, bottom, left, right) =>
new Promise((reslove, reject) => {
const DOM = document.createElement("canvas");
DOM.width = cWidth;
DOM.height = cHeight;
const ctx = DOM.getContext("2d");
const img = document.createElement("img");
img.src = originUrl;
img.onload = () => {
handleImg(
ctx,
img.naturalWidth,
img.naturalHeight,
img,
cWidth,
cHeight,
top,
bottom,
right,
left
);
reslove(DOM.toDataURL("image/png"));
};
img.onerror = (err) => reject(err);
});
export default drawImage;