如何使HTML5画布上的图像垂直和水平重复

How to make an image on a HTML5 canvas repeat vertically and horizontally?

本文关键字:垂直 水平 图像 HTML5 何使      更新时间:2023-09-26

我正在HTML5画布上绘制世界地图。我需要世界地图重复垂直和水平。我动态地将世界地图作为img标签添加到我的web应用程序的div中,并将其精灵化以显示世界的不同部分(取决于脚本中其他地方传递的数据)。例如,如果亚洲占据了div的左半部分,并且说,不是美洲,那么我不希望在右侧出现空白。我想让地图开始重复。所以我需要在画布上绘制图像来重复。

我在其他地方的stackoverflow上发现了这个,但它不适合我。D:

createFullMapImage: function(done){
var imageObj = new Image();
imageObj.onload = _.bind(function(){
   var canvas = document.createElement("canvas"),
       context = canvas.getContext('2d'),
       w = imageObj.width,
       h = imageObj.height;
   canvas.width = w;
   canvas.height = h;
   for(var w = 0; w < canvas.width; w += imageObj.width){
      for(var h = 0; h < canvas.height; h += imageObj.height){
          context.drawImage(imageObj, w, h);
      }
   }
   var canvasImage = canvas.toDataURL('image/png');
   done.call(this, canvasImage);
}, this);
imageObj.src = [src]
}

注:我尝试过为世界地图的URL设置一个带有background-image属性的div,并设置background-repeat,但由于某种原因,这会扭曲我想要的大小。

谢谢——Gaweyne

EDIT—RE:副本。作为HTML5画布的新手,我不清楚,从同一主题的另一个线程,我是否使用。fillrect()方法与。drawimage()方法相结合时,使图像src在画布上重复。

使用模式重复

// img is the image, ctx is the 2d context.
var pat=ctx.createPattern(img,"repeat");  // repeat the image as a pattern
ctx.fillStyle=pat;   // set the fill style
ctx.rect(0,0,150,100);  // create a rectangle
ctx.fill();            // fill it with the pattern.