我希望能够在HTML 5画布中放大鼠标下的点,例如放大Google Maps。我怎样才能做到这一点?
答案 0 :(得分:105)
更好的解决方案是根据缩放的变化简单地移动视口的位置。缩放点只是旧缩放中的点和要保持不变的新缩放。也就是说视口预缩放和缩放后的视口相对于视口具有相同的缩放比例。鉴于我们相对于原点进行缩放。您可以相应地调整视口位置:
scalechange = newscale - oldscale;
offsetX = -(zoomPointX * scalechange);
offsetY = -(zoomPointY * scalechange);
所以你可以在放大时向下平移,向右平移,相对于你缩放的点放大了多少。
答案 1 :(得分:50)
终于解决了它:
var zoomIntensity = 0.2;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var width = 600;
var height = 200;
var scale = 1;
var originx = 0;
var originy = 0;
var visibleWidth = width;
var visibleHeight = height;
function draw(){
// Clear screen to white.
context.fillStyle = "white";
context.fillRect(originx,originy,800/scale,600/scale);
// Draw the black square.
context.fillStyle = "black";
context.fillRect(50,50,100,100);
}
// Draw loop at 60FPS.
setInterval(draw, 1000/60);
canvas.onwheel = function (event){
event.preventDefault();
// Get mouse offset.
var mousex = event.clientX - canvas.offsetLeft;
var mousey = event.clientY - canvas.offsetTop;
// Normalize wheel to +1 or -1.
var wheel = event.deltaY < 0 ? 1 : -1;
// Compute zoom factor.
var zoom = Math.exp(wheel*zoomIntensity);
// Translate so the visible origin is at the context's origin.
context.translate(originx, originy);
// Compute the new visible origin. Originally the mouse is at a
// distance mouse/scale from the corner, we want the point under
// the mouse to remain in the same place after the zoom, but this
// is at mouse/new_scale away from the corner. Therefore we need to
// shift the origin (coordinates of the corner) to account for this.
originx -= mousex/(scale*zoom) - mousex/scale;
originy -= mousey/(scale*zoom) - mousey/scale;
// Scale it (centered around the origin due to the trasnslate above).
context.scale(zoom, zoom);
// Offset the visible origin to it's proper position.
context.translate(-originx, -originy);
// Update scale and others.
scale *= zoom;
visibleWidth = width / scale;
visibleHeight = height / scale;
}
<canvas id="canvas" width="600" height="200"></canvas>
键为@Tatarize pointed out,用于计算轴位置,使缩放后缩放点(鼠标指针)保持在同一位置。
最初鼠标距离角落mouse/scale
距离,我们希望鼠标下方的点在缩放后保持在同一位置,但距离角落mouse/new_scale
。因此,我们需要移动origin
(角落的坐标)来解释这一点。
originx -= mousex/(scale*zoom) - mousex/scale;
originy -= mousey/(scale*zoom) - mousey/scale;
scale *= zomm
然后剩下的代码需要应用缩放并转换为绘图上下文,因此它的原点与画布角一致。
答案 2 :(得分:25)
这实际上是一个非常困难的问题(数学上),而且我几乎在做同样的事情。我在Stackoverflow上问了一个类似的问题,但没有得到任何回复,但发布了DocType(StackOverflow for HTML / CSS)并得到了回复。查看http://doctype.com/javascript-image-zoom-css3-transforms-calculate-origin-example
我正在构建一个执行此操作的jQuery插件(使用CSS3 Transforms进行Google Maps样式缩放)。我已经让缩放到鼠标光标位工作正常,仍然试图弄清楚如何允许用户像在谷歌地图中那样拖动画布。当我开始工作时,我会在这里发布代码,但请查看上面的鼠标缩放到点部分的链接。
我没有意识到Canvas上下文中有scale和translate方法,你可以用CSS3实现同样的东西,例如。使用jQuery:
$('div.canvasContainer > canvas')
.css('-moz-transform', 'scale(1) translate(0px, 0px)')
.css('-webkit-transform', 'scale(1) translate(0px, 0px)')
.css('-o-transform', 'scale(1) translate(0px, 0px)')
.css('transform', 'scale(1) translate(0px, 0px)');
确保将CSS3 transform-origin设置为0,0(-moz-transform-origin:0 0)。使用CSS3变换可以放大任何东西,只需确保容器DIV设置为溢出:隐藏以阻止缩放的边缘溢出边缘。
是否使用CSS3变换,或者画布'自己的缩放和翻译方法是由您决定的,但请查看上面的链接以进行计算。
更新:嗯!我只是在这里发布代码而不是让你关注链接:
$(document).ready(function()
{
var scale = 1; // scale of the image
var xLast = 0; // last x location on the screen
var yLast = 0; // last y location on the screen
var xImage = 0; // last x location on the image
var yImage = 0; // last y location on the image
// if mousewheel is moved
$("#mosaicContainer").mousewheel(function(e, delta)
{
// find current location on screen
var xScreen = e.pageX - $(this).offset().left;
var yScreen = e.pageY - $(this).offset().top;
// find current location on the image at the current scale
xImage = xImage + ((xScreen - xLast) / scale);
yImage = yImage + ((yScreen - yLast) / scale);
// determine the new scale
if (delta > 0)
{
scale *= 2;
}
else
{
scale /= 2;
}
scale = scale < 1 ? 1 : (scale > 64 ? 64 : scale);
// determine the location on the screen at the new scale
var xNew = (xScreen - xImage) / scale;
var yNew = (yScreen - yImage) / scale;
// save the current screen location
xLast = xScreen;
yLast = yScreen;
// redraw
$(this).find('div').css('-moz-transform', 'scale(' + scale + ')' + 'translate(' + xNew + 'px, ' + yNew + 'px' + ')')
.css('-moz-transform-origin', xImage + 'px ' + yImage + 'px')
return false;
});
});
您当然需要调整它以使用画布比例和翻译方法。
更新2:刚刚注意到我正在使用transform-origin和translate。我已经设法实现了一个只使用比例并自行翻译的版本,请在此处查看http://www.dominicpettifer.co.uk/Files/Mosaic/MosaicTest.html等待图像下载然后使用鼠标滚轮进行缩放,还支持通过拖动图像进行平移。它使用的是CSS3 Transforms,但您应该可以对Canvas使用相同的计算。
答案 3 :(得分:7)
我使用c ++遇到了这个问题,我可能不应该只使用OpenGL矩阵开始...反正如果你使用的是一个控件,其原点是左上角,你想要的像谷歌地图一样平移/缩放,这是布局(使用allegro作为我的事件处理程序):
// initialize
double originx = 0; // or whatever its base offset is
double originy = 0; // or whatever its base offset is
double zoom = 1;
.
.
.
main(){
// ...set up your window with whatever
// tool you want, load resources, etc
.
.
.
while (running){
/* Pan */
/* Left button scrolls. */
if (mouse == 1) {
// get the translation (in window coordinates)
double scroll_x = event.mouse.dx; // (x2-x1)
double scroll_y = event.mouse.dy; // (y2-y1)
// Translate the origin of the element (in window coordinates)
originx += scroll_x;
originy += scroll_y;
}
/* Zoom */
/* Mouse wheel zooms */
if (event.mouse.dz!=0){
// Get the position of the mouse with respect to
// the origin of the map (or image or whatever).
// Let us call these the map coordinates
double mouse_x = event.mouse.x - originx;
double mouse_y = event.mouse.y - originy;
lastzoom = zoom;
// your zoom function
zoom += event.mouse.dz * 0.3 * zoom;
// Get the position of the mouse
// in map coordinates after scaling
double newx = mouse_x * (zoom/lastzoom);
double newy = mouse_y * (zoom/lastzoom);
// reverse the translation caused by scaling
originx += mouse_x - newx;
originy += mouse_y - newy;
}
}
}
.
.
.
draw(originx,originy,zoom){
// NOTE:The following is pseudocode
// the point is that this method applies so long as
// your object scales around its top-left corner
// when you multiply it by zoom without applying a translation.
// draw your object by first scaling...
object.width = object.width * zoom;
object.height = object.height * zoom;
// then translating...
object.X = originx;
object.Y = originy;
}
答案 4 :(得分:6)
我喜欢Tatarize's answer,但我会提供另一种选择。这是一个简单的线性代数问题,我提出的方法适用于平移,缩放,倾斜等。也就是说,如果你的图像已经被转换,它就能很好地工作。
缩放矩阵时,刻度位于点(0,0)。因此,如果您有一个图像并将其缩放2倍,则右下角的点将在x和y方向上加倍(使用[0,0]是图像左上角的约定)。
如果你想要缩放关于中心的图像,那么解决方案如下:(1)翻译图像使其中心位于(0,0); (2)按x和y因子缩放图像; (3)翻译图像。即。
myMatrix
.translate(image.width / 2, image.height / 2) // 3
.scale(xFactor, yFactor) // 2
.translate(-image.width / 2, -image.height / 2); // 1
更抽象地说,同样的策略适用于任何一点。例如,如果要在P:
点缩放图像myMatrix
.translate(P.x, P.y)
.scale(xFactor, yFactor)
.translate(-P.x, -P.y);
最后,如果图像已经以某种方式转换(例如,如果它被旋转,倾斜,平移或缩放),则需要保留当前转换。具体而言,上面定义的变换需要通过当前变换进行后乘(或右乘)。
myMatrix
.translate(P.x, P.y)
.scale(xFactor, yFactor)
.translate(-P.x, -P.y)
.multiply(myMatrix);
你有它。这是一个显示实际情况的插件。滚动点上的鼠标滚轮,你会发现它们一直保持不变。 (仅在Chrome中测试过。)http://plnkr.co/edit/3aqsWHPLlSXJ9JCcJzgH?p=preview
答案 5 :(得分:5)
这是我的面向中心图像的解决方案:
var MIN_SCALE = 1;
var MAX_SCALE = 5;
var scale = MIN_SCALE;
var offsetX = 0;
var offsetY = 0;
var $image = $('#myImage');
var $container = $('#container');
var areaWidth = $container.width();
var areaHeight = $container.height();
$container.on('wheel', function(event) {
event.preventDefault();
var clientX = event.originalEvent.pageX - $container.offset().left;
var clientY = event.originalEvent.pageY - $container.offset().top;
var nextScale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, scale - event.originalEvent.deltaY / 100));
var percentXInCurrentBox = clientX / areaWidth;
var percentYInCurrentBox = clientY / areaHeight;
var currentBoxWidth = areaWidth / scale;
var currentBoxHeight = areaHeight / scale;
var nextBoxWidth = areaWidth / nextScale;
var nextBoxHeight = areaHeight / nextScale;
var deltaX = (nextBoxWidth - currentBoxWidth) * (percentXInCurrentBox - 0.5);
var deltaY = (nextBoxHeight - currentBoxHeight) * (percentYInCurrentBox - 0.5);
var nextOffsetX = offsetX - deltaX;
var nextOffsetY = offsetY - deltaY;
$image.css({
transform : 'scale(' + nextScale + ')',
left : -1 * nextOffsetX * nextScale,
right : nextOffsetX * nextScale,
top : -1 * nextOffsetY * nextScale,
bottom : nextOffsetY * nextScale
});
offsetX = nextOffsetX;
offsetY = nextOffsetY;
scale = nextScale;
});
body {
background-color: orange;
}
#container {
margin: 30px;
width: 500px;
height: 500px;
background-color: white;
position: relative;
overflow: hidden;
}
img {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
max-width: 100%;
max-height: 100%;
margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<img id="myImage" src="http://s18.postimg.org/eplac6dbd/mountain.jpg">
</div>
答案 6 :(得分:3)
我想在这里提供一些信息,这些信息可以分别绘制图片并移动它们。
当您想要存储视口的缩放和位置时,这可能很有用。
这是抽屉:
function redraw_ctx(){
self.ctx.clearRect(0,0,canvas_width, canvas_height)
self.ctx.save()
self.ctx.scale(self.data.zoom, self.data.zoom) //
self.ctx.translate(self.data.position.left, self.data.position.top) // position second
// Here We draw useful scene My task - image:
self.ctx.drawImage(self.img ,0,0) // position 0,0 - we already prepared
self.ctx.restore(); // Restore!!!
}
注意比例必须是第一个。
这是zoomer:
function zoom(zf, px, py){
// zf - is a zoom factor, which in my case was one of (0.1, -0.1)
// px, py coordinates - is point within canvas
// eg. px = evt.clientX - canvas.offset().left
// py = evt.clientY - canvas.offset().top
var z = self.data.zoom;
var x = self.data.position.left;
var y = self.data.position.top;
var nz = z + zf; // getting new zoom
var K = (z*z + z*zf) // putting some magic
var nx = x - ( (px*zf) / K );
var ny = y - ( (py*zf) / K);
self.data.position.left = nx; // renew positions
self.data.position.top = ny;
self.data.zoom = nz; // ... and zoom
self.redraw_ctx(); // redraw context
}
当然,我们需要一个拖拉机:
this.my_cont.mousemove(function(evt){
if (is_drag){
var cur_pos = {x: evt.clientX - off.left,
y: evt.clientY - off.top}
var diff = {x: cur_pos.x - old_pos.x,
y: cur_pos.y - old_pos.y}
self.data.position.left += (diff.x / self.data.zoom); // we want to move the point of cursor strictly
self.data.position.top += (diff.y / self.data.zoom);
old_pos = cur_pos;
self.redraw_ctx();
}
})
答案 7 :(得分:3)
这是另一种使用setTransform()而不是scale()和translate()的方法。一切都存储在同一个对象中。假设画布在页面上为0,0,否则你需要从页面坐标中减去它的位置。
this.zoomIn = function (pageX, pageY) {
var zoomFactor = 1.1;
this.scale = this.scale * zoomFactor;
this.lastTranslation = {
x: pageX - (pageX - this.lastTranslation.x) * zoomFactor,
y: pageY - (pageY - this.lastTranslation.y) * zoomFactor
};
this.canvasContext.setTransform(this.scale, 0, 0, this.scale,
this.lastTranslation.x,
this.lastTranslation.y);
};
this.zoomOut = function (pageX, pageY) {
var zoomFactor = 1.1;
this.scale = this.scale / zoomFactor;
this.lastTranslation = {
x: pageX - (pageX - this.lastTranslation.x) / zoomFactor,
y: pageY - (pageY - this.lastTranslation.y) / zoomFactor
};
this.canvasContext.setTransform(this.scale, 0, 0, this.scale,
this.lastTranslation.x,
this.lastTranslation.y);
};
附带处理平移的代码:
this.startPan = function (pageX, pageY) {
this.startTranslation = {
x: pageX - this.lastTranslation.x,
y: pageY - this.lastTranslation.y
};
};
this.continuePan = function (pageX, pageY) {
var newTranslation = {x: pageX - this.startTranslation.x,
y: pageY - this.startTranslation.y};
this.canvasContext.setTransform(this.scale, 0, 0, this.scale,
newTranslation.x, newTranslation.y);
};
this.endPan = function (pageX, pageY) {
this.lastTranslation = {
x: pageX - this.startTranslation.x,
y: pageY - this.startTranslation.y
};
};
要自己推导出答案,请考虑相同的页面坐标需要匹配缩放前后的相同画布坐标。然后你可以从这个等式开始做一些代数:
(pageCoords - translation)/ scale = canvasCoords
答案 8 :(得分:2)
if(wheel > 0) {
this.scale *= 1.1;
this.offsetX -= (mouseX - this.offsetX) * (1.1 - 1);
this.offsetY -= (mouseY - this.offsetY) * (1.1 - 1);
}
else {
this.scale *= 1/1.1;
this.offsetX -= (mouseX - this.offsetX) * (1/1.1 - 1);
this.offsetY -= (mouseY - this.offsetY) * (1/1.1 - 1);
}
答案 9 :(得分:2)
这是@ tatarize的答案的代码实现,使用PIXI.js.我有一个视口看着一个非常大的图像的一部分(例如谷歌地图风格)。
$canvasContainer.on('wheel', function (ev) {
var scaleDelta = 0.02;
var currentScale = imageContainer.scale.x;
var nextScale = currentScale + scaleDelta;
var offsetX = -(mousePosOnImage.x * scaleDelta);
var offsetY = -(mousePosOnImage.y * scaleDelta);
imageContainer.position.x += offsetX;
imageContainer.position.y += offsetY;
imageContainer.scale.set(nextScale);
renderer.render(stage);
});
$canvasContainer
是我的html容器。imageContainer
是我的PIXI容器,其中包含图像。mousePosOnImage
是相对于整个图像的鼠标位置(不仅仅是视口)。以下是我如何获得鼠标位置:
imageContainer.on('mousemove', _.bind(function(ev) {
mousePosOnImage = ev.data.getLocalPosition(imageContainer);
mousePosOnViewport.x = ev.data.originalEvent.offsetX;
mousePosOnViewport.y = ev.data.originalEvent.offsetY;
},self));
答案 10 :(得分:0)
您需要在缩放前后获取世界空间中的点(与屏幕空间相对),然后按三角形进行平移。
mouse_world_position = to_world_position(mouse_screen_position);
zoom();
mouse_world_position_new = to_world_position(mouse_screen_position);
translation += mouse_world_position_new - mouse_world_position;
鼠标位置在屏幕空间中,因此您必须将其转换为世界空间。 简单的转换应该类似于:
world_position = screen_position / scale - translation
答案 11 :(得分:0)
你可以使用scrollto(x,y)函数来处理滚动条的位置,直到你需要在缩放后显示的点。找到鼠标使用event.clientX和event.clientY的位置。 this will help you
答案 12 :(得分:0)
一件重要的事情...如果你有类似的东西:
body {
zoom: 0.9;
}
您需要在画布上做适当的事情:
canvas {
zoom: 1.1;
}
答案 13 :(得分:0)
这是我用来更严格地控制事物绘制方式的方法
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var scale = 1;
var xO = 0;
var yO = 0;
draw();
function draw(){
// Clear screen
ctx.clearRect(0, 0, canvas.offsetWidth, canvas.offsetHeight);
// Original coordinates
const xData = 50, yData = 50, wData = 100, hData = 100;
// Transformed coordinates
const x = xData * scale + xO,
y = yData * scale + yO,
w = wData * scale,
h = hData * scale;
// Draw transformed positions
ctx.fillStyle = "black";
ctx.fillRect(x,y,w,h);
}
canvas.onwheel = function (e){
e.preventDefault();
const r = canvas.getBoundingClientRect(),
xNode = e.pageX - r.left,
yNode = e.pageY - r.top;
const newScale = scale * Math.exp(-Math.sign(e.deltaY) * 0.2),
scaleFactor = newScale/scale;
xO = xNode - scaleFactor * (xNode - xO);
yO = yNode - scaleFactor * (yNode - yO);
scale = newScale;
draw();
}
<canvas id="canvas" width="600" height="200"></canvas>