PrinzMaisle: Canvas über MouseWheel skalieren funktioniert nicht

Beitrag lesen

Hi,

habe leider keine Zeit den Code im Detail zu prüfen, aber hier eine Idee die sich auf den Zoom konzentriert.

<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>Canvas</title>
<style>
.canvas-container {
	text-align: center;
}
.canvas {
	border: 5px solid black;
	background-color: #fff;
}
</style>
</head>
<body>

<canvas id="canvas" width="800" height="600"></canvas>
<script type="text/javascript">
const zoomIntensity = 0.2;

const canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
const width = 800;
const height = 600;

let scale = 1;
let originx = 0;
let originy = 0;
let visibleWidth = width;
let visibleHeight = height;


function draw(){

    context.fillStyle = "white";
    context.fillRect(originx, originy, width/scale, height/scale);

    context.fillStyle = "black";
    context.fillRect(50, 50, 100, 100);


    window.requestAnimationFrame(draw);
}

draw();

canvas.onwheel = function (event){
    event.preventDefault();

    const mousex = event.clientX - canvas.offsetLeft;
    const mousey = event.clientY - canvas.offsetTop;

    const wheel = event.deltaY < 0 ? 1 : -1;

    const zoom = Math.exp(wheel * zoomIntensity);
    
    context.translate(originx, originy);

    originx -= mousex/(scale*zoom) - mousex/scale;
    originy -= mousey/(scale*zoom) - mousey/scale;
    
    context.scale(zoom, zoom);
    context.translate(-originx, -originy);

    scale *= zoom;
    visibleWidth = width / scale;
    visibleHeight = height / scale;
}

</script>


</body>
</html>