另一種使用模運算符來實現翻譯的方法。看到這個例子jsfiddle
使用圖像作爲房間和畫布作爲視口,以下代碼允許將房間看作是畫布中的環繞。
嘗試使用dx和dy的值來查看效果。 在實踐中不會
在
<img id='room'>
<canvas id='canv' width=100 height=75></canvas>
代碼
im=new Image();
im.src='http://www.all-sweets.com/gradient-wallpaper/gradient-background/gradient-background-3.jpg';
im.onload=function() {
document.getElementById('room').src=im.src;
c=document.getElementById('canv');
cx=c.getContext('2d');
cw=c.width;
ch=c.height;
iw=im.width;
ih=im.height;
x=0;//x value of top left corner of viewport
y=0;//y value of top left corner of viewport
//displacement much less than image width or height
//build up of displacement move viewport
/***************************************************************
Displacements would be set as viewport moves
Manually change these values below to see effect on viewport.
Shown image is 400px by 300px
set dx to 350 and dy to 260 for example to see overlap effect
****************************************************************/
dx=0;//displacement from current x
dy=0;//displacement from current y
//***************************************************************
x+=dx;//new x position
x=x%iw; //modulo translates relative to room coordinates
x=(x+iw)%iw;//deals with negative x
y+=dy;//new y position
y=y%ih;//modulo translates relative to room coordinates
y=(y+ih)%ih;//deals with negative y
if(x+cw<iw && y+ch<ih) { //totally inside room
cx.drawImage(im, x, y, cw, ch, 0, 0, cw, ch);
}
else if(x+cw>=iw && y+ch<ih) { //extends beyond room on right only
cx.drawImage(im, x, y, iw-x, ch, 0, 0, iw-x, ch);
cx.drawImage(im, 0, y, x+cw-iw, ch, iw-x, 0, x+cw-iw, ch);
}
else if(x+cw<iw && y+ch>=ih) {//extends beyond room at bottom only
cx.drawImage(im, x, y, cw, ih-y, 0, 0, cw, ih-y);
cx.drawImage(im, x, 0, cw, y+ch-ih, 0, ih-y, cw, y+ch-ih);
}
else {//extends beyond room on right and bottom
cx.drawImage(im, x, y, iw-x, ih-y, 0, 0, iw-x, ih-y);
cx.drawImage(im, 0, y, x+cw-iw, ih-y, iw-x, 0, x+cw-iw, ih-y);
cx.drawImage(im, x, 0, iw-x, y+ch-ih, 0, ih-y, iw-x, y+ch-ih);
cx.drawImage(im, 0, 0, x+cw-iw, y+ch-ih, iw-x, ih-y, x+cw-iw, y+ch-ih);
}
}
使用img標籤讓房間只能通過在畫布上的視窗可以看到,我想你有一個函數打印場景:首先你在'正常'的位置(假設與A矩形相匹配的位置)。然後,將場景向上移動場景的高度並重新打印(這樣,您可以打印C角);然後您將場景右移場景的寬度並重新打印(這樣您可以打印D角);最後你將場景向下移動到場景的高度,然後打印角落B.另請參閱http://www.w3schools.com/tags/canvas_translate.asp – Buch