js使用canvas实现图片鼠标滚轮放大缩小拖拽预览,显示像素坐标,显示像素值
以下是一个使用JavaScript和Canvas实现的图片鼠标滚轮缩放、拖拽以及显示像素坐标和像素值的简单示例代码:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var image = new Image();
var startX, startY, isDown = false;
var scale = 1;
image.onload = function() {
draw(true);
};
image.src = 'your-image-url.jpg'; // 替换为你的图片URL
function draw(firstTime) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, 0, 0, image.width * scale, image.height * scale);
if (!firstTime && isDown) {
ctx.drawImage(image, startX, startY, image.width * scale, image.height * scale);
}
}
canvas.addEventListener('mousedown', function(e) {
isDown = true;
startX = e.offsetX;
startY = e.offsetY;
});
canvas.addEventListener('mousemove', function(e) {
if (isDown) {
var x = e.offsetX - (startX - (canvas.width / 2 - startX));
var y = e.offsetY - (startY - (canvas.height / 2 - startY));
canvas.style.cursor = 'grabbing';
draw(false);
startX = x;
startY = y;
}
});
canvas.addEventListener('mouseup', function() {
isDown = false;
canvas.style.cursor = 'grab';
});
canvas.addEventListener('mousewheel', function(e) {
e.preventDefault();
var oldScale = scale;
scale += e.wheelDelta / 1000;
scale = Math.min(Math.max(scale, 1), 5); // Limit scale between 1 and 5
if (scale !== oldScale) {
var relX = e.offsetX - canvas.width / 2;
var relY = e.offsetY - canvas.height / 2;
draw(false);
}
});
canvas.addEventListener('click', function(e) {
var x = Math.floor(e.offsetX * (1 / scale));
var y = Math.floor(e.offsetY * (1 / scale));
var pixel = ctx.getImageData(x, y, 1, 1).data;
console.log('像素坐标: (' + x + ',' + y + ')');
console.log('像素值: R=' + pixel[0] + ', G=' + pixel[1] + ', B=' + pixel[2] + ', A=' + pixel[3]);
});
</script>
</body>
</html>
在这段代码中,我们首先定义了一个HTML页面,其中包含一个<canvas>
元素和一个JavaScript脚本。我们加载了一个图片资源,并在图片加载完成后将其绘制到画布上。我们实现了鼠标的拖拽功能来移动图片,鼠标滚轮的缩放功能来调整图片的大小,并在鼠标单击时获取并显示鼠标下方像素的坐标和像素值。
请注意,这个示例没有进行错误处理,并且假设用户的浏览器支持mousewheel
事件和getImageData
方法。对于生产环境,你可能需要添加更多的错误处理和兼容性代码。
评论已关闭