html代码
todo 实现画矩形框,圆形roi
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Image Viewer</title>
<style>canvas {border: 1px solid black;}
</style>
</head>
<body>
<div><button id="loadImageButton">Load Image</button>
</div>
<canvas id="mainCanvas" width="600" height="400"></canvas><script>const canvas = document.getElementById('mainCanvas');const ctx = canvas.getContext('2d');let imageObj = new Image();let imageWidth;let imageHeight;let scale = 1;let offsetX = 0;let offsetY = 0;canvas.addEventListener('mousedown', mouseDownListener);canvas.addEventListener('mouseup', mouseUpListener);canvas.addEventListener('mousemove', mouseMoveListener);canvas.addEventListener('mousewheel', mouseWheelListener);document.getElementById('loadImageButton').addEventListener('click', loadImage);function loadImage() {const input = document.createElement('input');input.type = 'file';input.accept = 'image/*';input.click();input.onchange = e => {const file = e.target.files[0];const reader = new FileReader();reader.onload = readerEvent => {const url = readerEvent.target.result;imageObj.src = url;};reader.readAsDataURL(file);};}let isDragging = false;let lastX;let lastY;function mouseDownListener(e) {let rect = canvas.getBoundingClientRect();isDragging = true;lastX = e.clientX - rect.left;lastY = e.clientY - rect.top;}function mouseUpListener(e) {isDragging = false;}function mouseMoveListener(e) {if (isDragging) {let rect = canvas.getBoundingClientRect();offsetX -= (e.clientX - rect.left) - lastX;offsetY -= (e.clientY - rect.top) - lastY;lastX = e.clientX - rect.left;lastY = e.clientY - rect.top;ctx.clearRect(0, 0, canvas.width, canvas.height);drawImage();}}function mouseWheelListener(e) {let delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));if (scale > 0.1 && scale < 10 && delta < 0) {scale *= 0.9;}if (scale > 0.1 && scale < 10 && delta > 0) {scale *= 1.1;}ctx.clearRect(0, 0, canvas.width, canvas.height);drawImage();}function drawImage() {ctx.drawImage(imageObj, -offsetX, -offsetY,imageWidth * scale,imageHeight * scale);}imageObj.onload = () => {imageWidth = imageObj.width;imageHeight = imageObj.height;drawImage();}
</script>
</body>
</html>