javascript - Make a canvas infinite - Stack Overflow

I am currently using a canvas on which I drew some areas of interest. They consist in squares and can b

I am currently using a canvas on which I drew some areas of interest. They consist in squares and can be moved by a mouse click (i.e : a selected area will center on my cursor position everytime I click on the canvas).

My current problem is that I would like to add the following feature: When I click near the edge of the canvas (either left or right), if a portion of the square is off-canvas, I want this off-canvas portion to appear at the opposite edfe.

Example: If I click near the right edge of the canvas, the hidden portion should appear on the left.

To be honest, I don't have any clue on how to do this properly. It seems to me that it requires a really heavy solution (with a lot of loops).

Your help would be very appreciated.

I am currently using a canvas on which I drew some areas of interest. They consist in squares and can be moved by a mouse click (i.e : a selected area will center on my cursor position everytime I click on the canvas).

My current problem is that I would like to add the following feature: When I click near the edge of the canvas (either left or right), if a portion of the square is off-canvas, I want this off-canvas portion to appear at the opposite edfe.

Example: If I click near the right edge of the canvas, the hidden portion should appear on the left.

To be honest, I don't have any clue on how to do this properly. It seems to me that it requires a really heavy solution (with a lot of loops).

Your help would be very appreciated.

Share Improve this question asked Jul 26, 2016 at 11:59 nugetcharnugetchar 1721 gold badge3 silver badges18 bronze badges 4
  • 1 I'd remend posting what you have so far so that at least people can see what might work and what might not. It's hard to troubleshoot with no code at all. – Toby Commented Jul 26, 2016 at 12:03
  • 1 You need to draw everything that overlaps the edge at least twice (once for each side it is visible) if it is in a corner an thus will be visible in every other corner you need to draw it 4 times once for each corner – Blindman67 Commented Jul 26, 2016 at 12:54
  • 1 Do you mean an infinite panorama? Here's an example. – markE Commented Jul 26, 2016 at 16:26
  • You can use the library called TiledCanvas It provides interfaces to zoom and move. And draw in an infinite space using all the canvas apis. It does require that you tell where you are drawing. github./Squarific/TiledCanvas This has the advantage that you don't have to do things like zooming or moving yourself. – urban Commented Dec 31, 2016 at 16:28
Add a ment  | 

1 Answer 1

Reset to default 7

The simple way to do this is

You have an object with width height, x,and y

obj = { x :?, y : ?, w : ? , h: ?}

You draw it

ctx.fillRect(obj.x, obj.y, obj.w, obj.h);

You have the screen/canvas size

canW = ?;
canH = ?;

When you draw the object check if it is touching the right edge. If so draw it again on the left side

if(obj.x + obj.w > canW){
   ctx.fillRect(obj.x - canW,obj.y, obj.w, obj.h);

Now as you are on the left side check that it's not on the bottom edge if it is draw it again at the top

   if(obj.y + obj.h > canH){
       ctx.fillRect(obj.x - canW, obj.y - canH, obj.w, obj.h);
   }

}

And the same for the bottom, But ass you have already done the top left in the above render you only need check this time for the bottom top

if(obj.y + obj.h > canH){
   ctx.fillRect(obj.x, obj.y - canH, obj.w, obj.h);
}

And you are done.

Demo shows a random infinite scrolling colored box scene.

var onResize;
function display(){  //
    ctx.setTransform(1,0,0,1,0,0); // reset transform
    ctx.globalAlpha = 1;           // reset alpha
    ctx.clearRect(0,0,w,h);
    if(array.length === 0){
        addRandomObjects();
    }
    // move the scene;
    offsetDX += (Math.random() + Math.random() + Math.random())/3 -0.5;
    offsetDY += (Math.random() + Math.random() + Math.random())/3 -0.5;
    offsetDX = Math.max(-4,Math.min(4,offsetDX));
    offsetDY = Math.max(-4,Math.min(4,offsetDY));
    offsetX += offsetDX;
    offsetY += offsetDY;
    offsetX = ((offsetX % w) + w) % w;
    offsetY = ((offsetY % h) + h) % h;
  
    // draw the scene;
    drawObjects();
    
}
var offsetX = 0;
var offsetY = 0;
var offsetDX = 0;
var offsetDY = 0;

var drawObjects = function(){
    var ox = offsetX;  // get the offset
    var oy = offsetY;
    for(i = 0; i < array.length; i ++){ // do each object
        var a = array[i];
        var x = (a.x + ox)%w;
        var y = (a.y + oy)%h;
        ctx.fillStyle = a.col;   
        ctx.fillRect(x,y,a.w,a.h); // draw it
        if(x+a.w > w){  // if touching right edge draw again at left
            ctx.fillRect(x-w,y,a.w,a.h);
            if(y+a.h > h){
                ctx.fillRect(x-w,y-h,a.w,a.h);
            }
              
        }
        if(y+a.h > h){ // if touching bottom draw again at top
            ctx.fillRect(x,y-h,a.w,a.h);
        }
    }

}

var array = [];

var addRandomObjects = function(){
    for(i = 0; i < 50; i++){
        var hue = Math.floor(Math.random() * 360);
        array.push({
            x: Math.random() * w,
            y : Math.random() * h,
            w : Math.max(50,Math.random() * (w * h * 0.0004)),
            h : Math.max(80,Math.random() * (w * h * 0.0004)),
            col: "hsla("+hue+",100%,50%,0.5)",
        })
    }
}

var onResize = function(){
    array = [];
}






/** SimpleFullCanvasMouse.js begin **/
//==================================================================================================
// The following code is boilerplate code that provides me with a standard interface to various forums.
// It provides a mouse interface, a full screen canvas, and some global often used variable  
// like canvas, ctx, mouse, w, h (width and height), globalTime
// This code is not intended to be part of the answer unless specified and has been formated to reduce
// display size. It should not be used as an example of how to write a canvas interface.
// By Blindman67
const U = undefined;const RESIZE_DEBOUNCE_TIME = 100;
var w,h,cw,ch,canvas,ctx,mouse,createCanvas,resizeCanvas,setGlobals,globalTime=0,resizeCount = 0; 
var L = typeof log === "function" ? log : function(d){ console.log(d); }
createCanvas = function () { var c,cs; cs = (c = document.createElement("canvas")).style; cs.position = "absolute"; cs.top = cs.left = "0px"; cs.zIndex = 1000; document.body.appendChild(c); return c;}
resizeCanvas = function () {
    if (canvas === U) { canvas = createCanvas(); } canvas.width = window.innerWidth; canvas.height = window.innerHeight; ctx = canvas.getContext("2d"); 
    if (typeof setGlobals === "function") { setGlobals(); } if (typeof onResize === "function"){ resizeCount += 1; setTimeout(debounceResize,RESIZE_DEBOUNCE_TIME);}
}
function debounceResize(){ resizeCount -= 1; if(resizeCount <= 0){ onResize();}}
setGlobals = function(){ cw = (w = canvas.width) / 2; ch = (h = canvas.height) / 2; }




resizeCanvas(); 
window.addEventListener("resize",resizeCanvas); 

function update(timer){ // Main update loop
    globalTime = timer;
    display();  // call demo code
    requestAnimationFrame(update);
}
requestAnimationFrame(update);

/** SimpleFullCanvasMouse.js end **/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745283142a4620398.html

相关推荐

  • javascript - Make a canvas infinite - Stack Overflow

    I am currently using a canvas on which I drew some areas of interest. They consist in squares and can b

    18小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信