1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <meta http-equiv="X-UA-Compatible" content="IE=edge" />
6 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7 <title>Document</title>
8 <script src="./konva.min.js"></script>
9 <style>
10 * {
11 margin: 0;
12 padding: 0;
13 }
14 body,
15 html {
16 padding: 5px;
17 }
18 #container {
19 background-color: pink;
20 width: 500px;
21 height: 500px;
22 margin: 0 auto;
23 }
24 </style>
25 </head>
26 <body>
27 <div id="container"></div>
28 <script>
29 var width = 500;
30 var height = 500;
31 var newScale = 1;
32 // where everything stands in Konvas
33 var stage = new Konva.Stage({
34 container: "container",
35 width: width,
36 height: height,
37 });
38
39 var layer = new Konva.Layer();
40
41 var rect1 = new Konva.Rect({
42 width: 100,
43 height: 100,
44 fill: "green",
45 stroke: "black",
46 strokeWidth: 0,
47 scaleX: newScale,
48 scaleY: newScale,
49 });
50 layer.add(rect1);
51 stage.add(layer);
52 document
53 .getElementById("container")
54 .addEventListener("wheel", function (e) {
55 if (e.deltaY <= 0) {
56 fangda();
57 } else {
58 suoxiao();
59 }
60 });
61 const fangda = () => {
62 console.log("向上-放大");
63 if (newScale < 1.2) {
64 const num = newScale + 0.01;
65 newScale = (num * 100) / 100;
66 let calcWidth = (rect1.width() - rect1.width() * newScale).toFixed(2);
67 let calcHeight = (rect1.width() - rect1.height() * newScale).toFixed(
68 2
69 );
70
71 console.table(
72 "calcWidth--" + calcWidth,
73 "calcHeight--" + calcHeight,
74 "缩小计算后的值--" + newScale
75 );
76 // if (calcWidth || calcHeight < 0) {
77 // calcWidth = Math.abs(calcWidth);
78 // calcHeight = Math.abs(calcHeight);
79 // }
80 rect1.offsetX(-calcWidth);
81 rect1.offsetY(-calcHeight);
82 rect1.scale({
83 x: newScale,
84 y: newScale,
85 });
86 }
87 };
88 const suoxiao = () => {
89 console.log("向下-缩小");
90 if (newScale > 0.5) {
91 const num = newScale - 0.01;
92 newScale = Math.floor(num * 100) / 100;
93
94 let calcWidth = rect1.width() - rect1.width() * newScale;
95 let calcHeight = rect1.height() - rect1.height() * newScale;
96
97 console.table(
98 "calcWidth--" + calcWidth,
99 "calcHeight--" + calcHeight,
100 "缩小计算后的值--" + newScale
101 );
102
103 rect1.offsetX(-calcWidth);
104 rect1.offsetY(-calcHeight);
105 rect1.scale({
106 x: newScale,
107 y: newScale,
108 });
109 }
110 };
111 </script>
112 <button onclick="fangda()">放大</button>
113 <button onclick="suoxiao()">缩小</button>
114 </body>
115 </html>