zoom-image-data
将指定宽高的图像缓冲区数据输出到另一宽高的图像缓冲区
1. 安装
npm install zoom-image-data
2. 构造
new zoomImageData(
param: {
inw: number,
inh: number,
outw: number,
outh: number,
cellRatio?: number,
cellWH?: number,
splitCell?: number,
splitCellSize?: number,
inData: ArrayBuffer,
outData: ArrayBuffer,
}
) => zoomImageData
3. API
translate(dx: number, dy: number, silent?: boolean) => void
zoom(cx: number, cy: number, ratio: number, silent?: boolean) => void
resize(silent?: boolean) => void
updateMatrix(scale: number, dx: number, dy: number) => void
inCoorIsIn(x: number, y: number) => boolean
outCoorIsIn(x: number, y: number) => boolean
transInToOut(coors: number[]) => number[]
transOutToIn(coors: number[]) => number[]
update() => number[]
zoom-image-data单元像素可以不等比转移到输出图像缓冲区中,且支持放大到一定倍率之后显示分割线
5. 使用
以下为将一个原宽高为10*10的图像按宽高比为2绘制到指定宽高canvas元素
html
<canvas id="canvas"></canvas>
css
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
}
javascript
import { zoomImageData } from 'zoom-image-data';
window.onload = function () {
const canvas = document.getElementById('canvas');
const inw = 10;
const inh = 10;
const inData = new ArrayBuffer(inw * inh * 4);
const outw = document.body.clientWidth;
const outh = document.body.clientHeight;
const outImageData = new ImageData(outw, outh);
canvas.width = outw;
canvas.height = outh;
const ctx = canvas.getContext('2d');
const transferImageData = new ZoomImageData({
inw,
inh,
inData,
outw,
outh,
outData: outImageData.data.buffer,
cellRatio: 2,
cellWH: 8,
splitCell: true,
splitCellSize: 8,
})
let isDirty = true;
fillInData();
requestAnimationFrame(update);
function update() {
requestAnimationFrame(update);
if (!isDirty) return;
isDirty = false
transferImageData.update();
ctx.putImageData(outImageData, 0, 0);
}
function fillInData() {
transferImageData.inData.fill(4291611705);
}
function getPosition(e) {
let rect = canvas.getBoundingClientRect();
return [e.pageX - rect.left, e.pageY - rect.top];
}
document.addEventListener('keyup', function (e) {
transferImageData.resize();
isDirty = true;
})
canvas.addEventListener('wheel', function (e) {
const coor = getPosition(e);
transferImageData.zoom(coor[0], coor[1], e.deltaY < 0 ? 1.1 : 0.9);
isDirty = true;
})
let pos;
canvas.addEventListener('mousedown', function (e) {
pos = getPosition(e);
document.addEventListener('mousemove', mousemove)
document.addEventListener('mouseup', mouseup)
})
function mousemove(e) {
const cur = getPosition(e);
transferImageData.translate(cur[0] - pos[0], cur[1] - pos[1]);
pos = cur;
isDirty = true;
}
function mouseup() {
document.removeEventListener('mousemove', mousemove)
document.removeEventListener('mouseup', mouseup)
}
}