我正在尝试实现由 Canvas 上的鼠标移动控制的无限背景场景滚动
我的 requestAnimationFrame 中的以下内容几乎可以正常工作
y1 = y1 >= h? y1 - h : y1; // y1 is the current mouse position on('drag') less the offset if the position is greater than height of canvas reset with offset
c.font="20px Georgia";
c.clearRect(0,0, w, h); // w, h is the width and height of canvas
c.save();
//c.translate(0, y1);
for (var i = 0; i < numImages; i++) { // number of images to be drawn to fill area
var y = y1 + (i * im.height); // reposition the images relative to mouse position
y = y >= h? - im.height + y1 : y; // if the image position is off screen then re position to top relative to mouse
c.drawImage(im, 0, y, im.width, im.height);
}
c.fillText("y: " + y,10,190);
c.restore();
但是,当我到达 Canvas 边缘的末端并需要“循环”图像时,问题就出现了......无法弄清楚如何在相对于鼠标位置离开 View 后重新定位图像
对此有什么见解吗?
更新:
我能够获得连续滚动,但我相信它被文档元素上的 e.preventDefault 弄乱了,而我正在 canvas 元素 本身上运行 'touchmove'...
在 Canvas 上运行代码还是在文档上运行代码更安全?
最佳答案
这是创建无限全景的一种方法:
从源图像创建水平镜像图像。
创建一个动画循环,首先绘制原始图像,然后绘制原始图像右侧的镜像。
视觉上向右平移:每次循环时,图像向左偏移 1 像素(偏移--)。当偏移量为原图+镜像宽度的大小时,则将偏移量重置为零。
向左平移视觉:以偏移量=-(原始+镜像宽度)开始,每次循环时,将图像向右偏移 1 像素 (offset++)。当偏移量为零时,则将偏移量重置为-(原始+镜像)。
鼠标控制:您可以使用鼠标 X 位置来确定计算所需的偏移量(进而确定您在无限全景图中的位置)。
var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var infiniteImage; var infiniteImageWidth; var img=document.createElement("img"); img.onload=function(){ // use a tempCanvas to create a horizontal mirror image // This makes the panning appear seamless when // transitioning to a new image on the right var tempCanvas=document.createElement("canvas"); var tempCtx=tempCanvas.getContext("2d"); tempCanvas.width=img.width*2; tempCanvas.height=img.height; tempCtx.drawImage(img,0,0); tempCtx.save(); tempCtx.translate(tempCanvas.width,0); tempCtx.scale(-1,1); tempCtx.drawImage(img,0,0); tempCtx.restore(); infiniteImageWidth=img.width*2; infiniteImage=document.createElement("img"); infiniteImage.onload=function(){ pan(); } infiniteImage.src=tempCanvas.toDataURL(); } img.crossOrigin="anonymous"; img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/mountain.jpg"; var fps = 60; var offsetLeft=0; function pan() { // increase the left offset offsetLeft+=1; if(offsetLeft>infiniteImageWidth){ offsetLeft=0; } ctx.drawImage(infiniteImage,-offsetLeft,0); ctx.drawImage(infiniteImage,infiniteImage.width-offsetLeft,0); setTimeout(function() { requestAnimationFrame(pan); }, 1000 / fps); }
body{ background-color: ivory; } canvas{border:1px solid red;}
<h4>Infinite panorama using mirror image</h4> <canvas id="canvas" width=500 height=143></canvas>
关于javascript - 通过鼠标移动在 Canvas 上滚动内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25893447/