Moving the start position of canvas pattern

后端 未结 3 831
误落风尘
误落风尘 2020-12-09 05:14

I have a code:

function draw(ctx) {
  // create new image object to use as pattern
  var img = new Image();
  img.onload = function(){
    // create pattern
         


        
相关标签:
3条回答
  • 2020-12-09 05:44

    You can achieve this by translating the canvas, drawing on it, and then translating it back to where you started:

    function draw(ctx) {
        // create new image object to use as pattern
        var img = new Image();
        img.onload = function(){
            // create pattern
            var ptrn = ctx.createPattern(img,'repeat');
            ctx.fillStyle = ptrn;
    
            // offset vars
            var offset_x = 60;
            var offset_y = 75;
            var fill_x = 500; // could be canvas.width
            var fill_y = 500; // could be canvas.height
    
            // offset
            ctx.translate(offset_x, offset_y);
    
            // draw
            ctx.fillRect(-offset_x, -offset_y, fill_x, fill_y);
    
            // undo offset
            ctx.translate(-offset_x, -offset_y);
        }
        img.src = 'images/wallpaper.png?' + new Date().getTime();
    }
    
    0 讨论(0)
  • 2020-12-09 05:47

    In response to the accepted answer: rather than undo the offset, I would use save() & restore() to avoid potential problems:

    ctx.save();
    ctx.translate(offset_x, offset_y);
    ctx.fillRect(-offset_x, -offset_y, fill_x, fill_y);
    ctx.restore();
    
    0 讨论(0)
  • 2020-12-09 05:56

    More general, complex transforms of the pattern alone are easily done. The trick is to do them immediately before the call to fill() or stroke().

    function draw(ctx) {
        // create new image object to use as pattern
        var img = new Image();
        img.onload = function(){
            // create pattern
            var ptrn = ctx.createPattern(img,'repeat');
            ctx.fillStyle = ptrn;
            ctx.beginPath();
            ctx.rect(0, 0, 150, 150);
    
            ctx.translate(-33, -33);
            ctx.fill();
        }
    
        img.src = 'images/wallpaper.png?' + new Date().getTime();
    }
    
    0 讨论(0)
提交回复
热议问题