本文介绍了移动画布图案的起始位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码:

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.fillRect(0,0,150,150);
  }
  img.src = 'images/wallpaper.png?' + new Date().getTime();
}

如何移动模式图片的起始位置?

How can i move the start position of pattern image?

推荐答案

您可以通过翻译画布,绘制它,然后将其翻译回您开始的位置来实现:

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();
}

这篇关于移动画布图案的起始位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:09