我想实现像Konva js https://jsfiddle.net/kiksy/jqo2h3dx/2/中那样的无限拖动。谁能帮我这个。我尝试各种各样的东西,但没有一个还可以。我是p5js和javascript中的新手。请提供任何提示。仅此元素阻止我完成整个项目。
var grid;
var current_img;
var BgCat1 = [];
var layerOne;
let show_grid = false;
function preload() {
img1 = loadImage(
"https://raw.githubusercontent.com/Rabbid76/graphics-snippets/master/resource/texture/fish64.png"
);
}
function setup() {
let cnv = createCanvas(1000, 1000);
colorMode(HSB, 255);
layerOne = createGraphics(1000, 1000);
layerOne.grid = new Grid(40);
const background_btn1 = select("#BgCategory1-btn1");
background_btn1.mousePressed(a);
}
function draw() {
background(0);
if (show_grid == true) {
layerOne.grid.display();
}
}
function a() {
show_grid = true;
current_img = img1;
}
class Grid {
constructor(cellSize) {
this.cellSize = cellSize;
this.numberOfColumns = floor(width / this.cellSize);
this.numberOfRows = floor(height / this.cellSize);
this.cells = new Array(this.numberOfColumns);
for (var column = 0; column < this.numberOfColumns; column++) {
this.cells[column] = new Array(this.numberOfRows);
}
for (var column = 0; column < this.numberOfColumns; column++) {
for (var row = 0; row < this.numberOfRows; row++) {
this.cells[column][row] = new Cell(column, row, cellSize);
}
}
}
display() {
for (var column = 0; column < this.numberOfColumns; column++) {
for (var row = 0; row < this.numberOfRows; row++) {
this.cells[column][row].show_cell();
}
}
}
}
class Cell {
constructor(column, row, size) {
this.x = column;
this.y = row;
this.w = size;
}
show_cell() {
image(current_img, this.x * this.w, this.y * this.w, this.w, this.w);
}
}
<html>
<button onclick="a()" id="BgCategory1-btn1">image 1</button>
</html>
可能有一个更优雅的解决方案,但是在这里我在网格的每一侧都绘制了一个额外的单元格来处理环绕效果,因此可见的12x12网格具有10x10的可见度。看到它在这里运行:https://editor.p5js.org/rednoyz/sketches/uJCADfZXv
let dim = 10, sz;
let xoff = 0, yoff = 0;
function setup() {
createCanvas(400, 400);
sz = width/ dim;
}
function mouseDragged() {
xoff += mouseX - pmouseX;
yoff += mouseY - pmouseY;
}
function draw() {
background(255);
for (let i = 0; i < dim+2; i++) {
for (let j = 0; j < dim+2; j++) {
let x = ((xoff + j * sz) % (width+sz)) - sz;
if (x < -sz) x += width+sz;
let y = ((yoff + i * sz) % (height+sz)) - sz;
if (y < -sz) y += height+sz;
rect(x, y, sz, sz);
text(i * 10 + j, x + sz/2, y + sz/2);
}
}
}