feat: add board scroll func

This commit is contained in:
chenshenhai 2021-05-25 11:15:38 +08:00
parent 2f580a3569
commit dcf5fae055
4 changed files with 50 additions and 8 deletions

View file

@ -25,11 +25,11 @@
</div>
<div>
<span>scrollX</span>
<input id="scaleX" type="number"/>
<input id="scrollX" type="number" value="0"/>
</div>
<div>
<span>scrollY</span>
<input id="scrollY" type="number"/>
<input id="scrollY" type="number" value="0"/>
</div>
<script src="./../../dist/index.global.js"></script>

View file

@ -0,0 +1,22 @@
const inputX = document.querySelector('#scrollX');
const inputY = document.querySelector('#scrollY');
let hasInited = false;
export function onScroll(board) {
if (hasInited === true) return;
inputX.addEventListener('change', () => {
const val = inputX.value * 1;
if (val > 0) {
board.scrollX(val);
board.draw();
}
});
inputY.addEventListener('change', () => {
const val = inputY.value * 1;
if (val > 0) {
board.scrollY(val);
board.draw();
}
});
hasInited = true;
}

View file

@ -1,5 +1,6 @@
import { draw } from './lib/draw.js';
import { onScale } from './lib/scale.js';
import { onScroll } from './lib/scroll.js';
const { Board } = window.iDraw;
@ -12,6 +13,7 @@ const board = new Board(mount, {
draw(board);
onScale(board);
onScroll(board);
// board.scale(2);
// board.draw();

View file

@ -22,6 +22,8 @@ class Board {
private _ctx: Context;
private _displayCtx: CanvasRenderingContext2D;
private _scaleRatio: number = 1;
private _scrollX: number = 0;
private _scrollY: number = 0;
// private _watcher: Watcher;
constructor(mount: HTMLDivElement, opts: Options) {
@ -43,16 +45,21 @@ class Board {
}
scale(scaleRatio: number) {
this._scaleRatio = scaleRatio;
if (scaleRatio > 0) this._scaleRatio = scaleRatio;
}
scrollX(x: number) {
if (x > 0) this._scrollX = x;
}
scrollY(y: number) {
if (y > 0) this._scrollY = y;
}
draw() {
this.clear();
this._displayCtx.drawImage(
this._canvas, 0, 0,
this._canvas.width * this._scaleRatio,
this._canvas.height * this._scaleRatio,
);
const size = this._calculateSize();
this._displayCtx.drawImage(this._canvas, size.x, size.y, size.w, size.h);
}
clear() {
@ -87,6 +94,17 @@ class Board {
return { ...defaultOpts, ...opts }
}
private _calculateSize(): { x: number; y: number; w: number; h: number } {
const { _scrollX, _scrollY, _scaleRatio, } = this;
const { devicePixelRatio: pxRatio, width, height } = this._opts;
const size = { x: 0, y: 0, w: width * pxRatio, h: height * pxRatio };
size.x = _scrollX * pxRatio * _scaleRatio;
size.y = _scrollY * pxRatio * _scaleRatio;
size.w = width * pxRatio * _scaleRatio;
size.h = height * pxRatio * _scaleRatio;
return size;
}
}