问题描述
我正在尝试在 HTML5 的画布内实现平移"功能,但我不确定实现它的最佳方法.
I'm trying to implement functionality to "pan" inside a canvas in HTML5 and I am unsure about the best way to go about accomplishing it.
目前 - 我正在尝试检测鼠标在画布上的位置,如果它在边缘的 10% 范围内,它将朝那个方向移动,如图所示:
Currently - I am trying to detect where the mouse is on the canvas, and if it is within 10% of an edge, it will move in that direction, as shown:
当前边缘检测:
canvas.onmousemove = function(e)
{
var x = e.offsetX;
var y = e.offsetY;
var cx = canvas.width;
var cy = canvas.height;
if(x <= 0.1*cx && y <= 0.1*cy)
{
alert("Upper Left");
//Move "viewport" to up and left (if possible)
}
//Additional Checks for location
}
我知道我可以通过在画布中创建路径并将事件附加到它们来实现这一点,但我没有经常使用它们,所以我想我会在这里问.另外 - 如果一个包装"平底锅是可能的,那就太棒了(向左平移最终会向右).
I know I could probably accomplish this by creating paths within the canvas and attaching events to them, but I haven't worked with them much, so I thought I would ask here. Also - if a "wrapping" pan would be possible that would be awesome (panning to the left will eventually get to the right).
总结:我想知道在 HTML5 Canvas 内完成平移"的最佳途径是什么.这不会使用图像,而是使用实际绘制的对象(如果这有什么不同的话).如果可以的话,我很乐意回答任何问题.
Summary: I am wondering what the best route is to accomplish "panning" is within the HTML5 Canvas. This won't be using images but actual drawn objects (if that makes any difference). I'll be glad to answer any questions if I can.
演示:
演示
推荐答案
这取决于您希望如何实现鼠标移动平移,但今天它通常是实时"平移,因为您可以四处拖动.我试着稍微更新一下你的小提琴:http://jsfiddle.net/pimvdb/VWn6t/3/.
It depends on how you want panning with mouse movement to be implemented, but today it's often 'realtime' panning in that you can drag around. I tried to update your fiddle a little: http://jsfiddle.net/pimvdb/VWn6t/3/.
var isDown = false; // whether mouse is pressed
var startCoords = []; // 'grab' coordinates when pressing mouse
var last = [0, 0]; // previous coordinates of mouse release
canvas.onmousedown = function(e) {
isDown = true;
startCoords = [
e.offsetX - last[0], // set start coordinates
e.offsetY - last[1]
];
};
canvas.onmouseup = function(e) {
isDown = false;
last = [
e.offsetX - startCoords[0], // set last coordinates
e.offsetY - startCoords[1]
];
};
canvas.onmousemove = function(e)
{
if(!isDown) return; // don't pan if mouse is not pressed
var x = e.offsetX;
var y = e.offsetY;
// set the canvas' transformation matrix by setting the amount of movement:
// 1 0 dx
// 0 1 dy
// 0 0 1
ctx.setTransform(1, 0, 0, 1,
x - startCoords[0], y - startCoords[1]);
render(); // render to show changes
}
这篇关于基于鼠标移动的 HTML5 平移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!