原生js实现图像分割与下载
利用
canvas
大法可以做很多NB的事🤩
步骤
1.输入要切割的行和列
2.点击开拆就可分割图片
3.点击分割后的图片直接进行下载
4.点击全部下载可一键下载所有分割后的图片(十张以上图片下载会有一定的问题,暂时定位到创建a
标签时候有些许不同步)
代码
HTML
<body>
<img id="source" src="https://mdn.mozillademos.org/files/5397/rhino.jpg" alt="">
<div>
行<input id="inp1" type="text" value="2">
列<input id="inp2" type="text" value="2">
<button id="clip_image">开拆</button>
<button id="download_image">全部下载</button>
</div>
<div id="allCanvas"></div>
<div></div>
</body>
JavaScript
let row = 2
let column = 3
// 拆分图片
document.getElementById("clip_image").onclick = function (){
clearImage()
row = (document.getElementById('inp1').value);
column = (document.getElementById('inp2').value);
const image = document.getElementById('source');
const width = image.width/column
const height = image.height/row
for (let i=1;i<=row * column;i++){
let canvasDom = document.createElement("canvas")
canvasDom.id = 'canvas' + i
canvasDom.width = width
canvasDom.height = height
canvasDom.style.marginRight ='5px'
canvasDom.onclick = func
document.getElementById('allCanvas').appendChild(canvasDom)
if (i%Number(column)===0){
let brDom = document.createElement("br")
document.getElementById('allCanvas').appendChild(brDom)
}
const canvas = document.getElementById('canvas'+i);
const ctx = canvas.getContext("2d");
ctx.drawImage(image, width * Math.floor((i-1) % column), height * Math.floor((i-1) / column), width, height, 0, 0, width, height);
}
}
// 全部下载
document.getElementById("download_image").onclick = function (){
let allCanvas = document.getElementsByTagName("canvas")
let canvas = null
console.log(allCanvas);
if (allCanvas.length !== 0){
for (let i=0;i<allCanvas.length;i++){
canvas = document.getElementById(allCanvas[i].id)
downLoad(canvas.toDataURL("image/png"), i);
}
} else {
alert('没拆开的东西咋下载')
}
}
// 清除canvas节点
function clearImage(){
let allCanvas = document.getElementsByTagName("canvas")
let allBr = document.getElementsByTagName("br")
for (let i=allCanvas.length-1;i>=0;i--){
(allCanvas[i]).remove()
if (i%column === 0){
(allBr[Math.floor(i/column)]).remove()
}
}
for (let i=allBr.length-1;i>=0;i--){
(allBr[i]).remove()
}
}
// 单个图片下载
function func(data) {
let canvas = document.getElementById(data.target.id)
// base64编码
// console.log(canvas.toDataURL("image/png"));
// 设定图片格式
downLoad(canvas.toDataURL("image/png"));
}
// 下载函数
function downLoad(url, i){
console.log(i);
const oA = document.createElement("a");
oA.download = '';// 设置下载的文件名,默认是'下载'
oA.href = url;
document.body.appendChild(oA);
oA.click();
oA.remove(); // 下载之后把创建的元素删除
}