Hi I’m working on a HTML5 Canvas whiteboard.
Now I’m facing the problem, that the background grid looks weird if I zoom out.
Everything is stored in objects and I clear and redraw the stage on changes.
This is my grid class:
class Grid {
constructor(
x=0, y=0, width=0, height=0, scalesize=60
) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.scalesize = scalesize;
}
draw() {
let {
x,y,width, height,scalesize
} = this;
let distX = dx%60;
let distY = dy%60;
x -= distX;
y -= distY;
for(let i = x; i<canvas.width; i += scalesize)
{
ctx.beginPath();
ctx.setLineDash([]);
ctx.shadowColor='#00000000';
ctx.moveTo(i,0);
ctx.lineTo(i,canvas.height);
ctx.strokeStyle= "#ccc";
ctx.stroke();
}
for(let i = y; i<canvas.height; i += scalesize)
{
ctx.beginPath();
ctx.setLineDash([]);
ctx.shadowColor='#00000000';
ctx.moveTo(0,i);
ctx.lineTo(canvas.width,i);
ctx.strokeStyle= "#ccc";
ctx.stroke();
}
}
}
scaleSize is the size of each grid field. Currently it’s 60.
And this is my scale function:
// ----------------------------------------------
// scaling
// ----------------------------------------------
let scaleAmount = 1.00;
let scaleAnimation;
let animationReady = false;
let scalePercent = parseInt(scaleSize.innerText.replace("%",""));
function scaleUpdate()
{
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.scale(scaleAmount, scaleAmount);
scaleSize.innerText = parseInt(parseFloat(scaleAmount.toFixed(1))*100)+"%";
stageUpdate();
}
function scale(direction)
{
let targetScale ;
if(direction=="zoomIn")
{
targetScale = (scalePercent / 100) + 0.1;
scaleAmount += 0.01;
animationReady = scaleAmount > targetScale;
targetScale= parseFloat(targetScale.toFixed(3));
scaleAmount = parseFloat(scaleAmount.toFixed(3));
dx += scaleAmount;
dy += scaleAmount;
}
if(direction=="zoomOut")
{
targetScale = (scalePercent / 100) - 0.1;
scaleAmount -= 0.01;
animationReady = scaleAmount < targetScale;
targetScale= parseFloat(targetScale.toFixed(3));
scaleAmount = parseFloat(scaleAmount.toFixed(3));
dx -= scaleAmount;
dy -= scaleAmount;
}
if (animationReady) {
scaleAmount = targetScale;
scalePercent = parseInt(scaleSize.innerText.replace("%",""));
} else {
scaleAnimation = requestAnimationFrame(() => {
scaleUpdate();
scale(direction);
});
}
}
Tell me, if you need more infos.
I hope someone can help me to fix the problem.
Thanks in advance
Frank




