js如何对二维数组进行拉伸或者缩放?

2023-06-27 357 0

怎么样对二维数组进行拉伸/缩放?

就是以下这道题目,只不过不是根据倍数缩放,而是自定义新数组的宽高
https://blog.csdn.net/qq_45371853/article/details/120169697

假设有二维数组arr,宽等于2,高等于2。
1.数组左上角区域值是2,右下角区域值是1,拉伸后的数组也要大概保持这个比例.
2.原数组只有0,1,2这3个值,新数组也只能有这3个值

let arr = [
    [2, 0],
    [0, 1]
];

拉伸成宽等于4,高等于4,的数组就是:

[
    [2,2,0,0],
    [2,2,0,0],
    [0,0,1,1],
    [0,0,1,1]
];

拉伸成宽等于4,高等于3,的数组就是:

[
    [2,2,0,0],
    [2,2,0,0],
    [0,0,1,1],
];
或
[
    [2,2,0,0],
    [0,0,1,1],
    [0,0,1,1],
];
function scale(list, newW, newH) {
return Array.from({length: newH}, (_, y) => {
return Array.from({length: newW}, (_, x) =>
list[y / newH * list.length | 0][x / newW * list[0].length | 0]
)
})
}
function scaleList(list, scaleX, scaleY) {
let height = list.length
let width = list[0].length
let nheight = height * scaleY | 0
let nwidth = width * scaleX | 0
let res = new Array(nheight)
for(let h = 0; h < nheight; h++){
let y = h / scaleY | 0
if(nheight % scaleY === 0){
let arr = new Array(nwidth)
for(let w = 0; w < nwidth; w++){
let x = w / scaleX | 0
arr[w] = list[y][x]
}
res[h] = arr
}else{
res[h] = [...res[y]]
}
}
return res
}

image.png

function scaleArray(originalArray, newWidth, newHeight) {
    let originalHeight = originalArray.length;
    let originalWidth = originalArray[0].length;
    let result = new Array(newHeight);
    for (let i = 0; i < newHeight; i++) {
        result[i] = new Array(newWidth);
        for (let j = 0; j < newWidth; j++) {
            // 计算新数组中的元素在原始数组中的对应位置
            let originalI = Math.floor(i * originalHeight / newHeight);
            let originalJ = Math.floor(j * originalWidth / newWidth);
            result[i][j] = originalArray[originalI][originalJ];
        }
    }
    return result;
}
let arr = [
    [2, 0],
    [0, 1]
];
console.log(scaleArray(arr, 4, 3));

回答

相关文章

nuxt2部署静态化和ssr的时候访问首页先报404再出现首页为什么?
`clip-path` 如何绘制圆角平行四边形呢?
多线程wait方法报错?
VUE 绑定的方法如何直接使用外部函数?
vue2固定定位该怎么做?
谁有redis实现信号量的代码,希望借鉴一下?