<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>canvas局部放大</title>
</head>
<body>
<p>
<canvas id="canvas"></canvas>
<canvas id="zoom"></canvas>
<div>
<label for="smoothbtn">
<input type="checkbox" name="smoothbtn" checked="checked" id="smoothbtn" />
启用图像平滑
</label>
</div>
<input type="file" accept="image" id="file">
</p>
</body>
<script>
const file = document.getElementById('file')
let url
file.addEventListener('change', e => {
url = URL.createObjectURL(e.target.files[0])
init()
})
function init() {
const img = new Image();
img.src = url
img.onload = function () {
draw(this);
};
function draw(img) {
const canvas = document.getElementById("canvas");
canvas.width = 500
canvas.height = img.height
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
img.style.display = "none";
const zoo = document.getElementById("zoom")
zoo.width = canvas.width
zoo.height = canvas.height
const zoomctx = zoo.getContext("2d");
const smoothbtn = document.getElementById("smoothbtn");
const toggleSmoothing = function (event) {
zoomctx.imageSmoothingEnabled = this.checked;
zoomctx.mozImageSmoothingEnabled = this.checked;
zoomctx.webkitImageSmoothingEnabled = this.checked;
zoomctx.msImageSmoothingEnabled = this.checked;
};
smoothbtn.addEventListener("change", toggleSmoothing);
const zoom = function (event) {
const x = event.layerX;
const y = event.layerY;
zoomctx.drawImage(
canvas,
Math.abs(x - 5),
Math.abs(y - 5),
10,
10,
0,
0,
canvas.width,
canvas.height,
);
};
canvas.addEventListener("mousemove", zoom);
}
}
</script>
</html>
原创文章,作者:guozi,如若转载,请注明出处:https://www.sudun.com/ask/88430.html