【问题标题】:How to change image repeat pattern in HTML5 Canvas如何在 HTML5 Canvas 中更改图像重复模式
【发布时间】:2021-01-02 03:47:58
【问题描述】:

我正在尝试创建许多不同的图像重复模式。我将以下代码用于重复模式。该代码适用于常规模式,但我需要许多不同的模式集,如下图所示。

或如下所示...

但是使用下面的代码,我只有这个模式在这里......

<div style="width: 675px;height:675px;overflow: hidden;"><canvas id="cc" width="300px" height="300px"></canvas></div>

<script>
    drawPattern(img, current_size);
    function drawPattern(img, size) {
         var canvas = document.getElementById('cc');
         
         var tempCanvas = document.createElement("canvas"),
             tCtx = tempCanvas.getContext("2d");
    
         tempCanvas.width = size;
         tempCanvas.height = size;
         tCtx.drawImage(img, 0, 0, img.width, img.height, 0, 0, size, size);
    
         // use getContext to use the canvas for drawing
         var ctx = canvas.getContext('2d');
         ctx.clearRect(0, 0, canvas.width, canvas.height);
         ctx.fillStyle = ctx.createPattern(tempCanvas, 'repeat');
         
         ctx.beginPath();
         ctx.rect(0,0,canvas.width,canvas.height);
         ctx.fill();
    
    }

</script>

请帮助我如何获得不同的模式。提前致谢。

【问题讨论】:

  • 您可以使用setTransform developer.mozilla.org/en-US/docs/Web/API/… 和相关函数更改图像的绘制方式和图案。例如,水平镜像模式绘制图像两次,一次正常,一次沿 x 镜像。同时增加画布大小以适应两个图像,例如var w = size;cc.width = w*2; cc.height = w; tCtx.drawImage(img, 0, 0, w, w); tCtx.setTransform(-1,0,0,1,w*2,0); tCtx.drawImage(img, w* 2, 0, w, w); var pat = tCtx.createPattern(cc,"repeat") 使用ctx.fillStyle = pat
  • 太好了,真的很有帮助。谢谢! @盲人67

标签: javascript html5-canvas html2canvas


【解决方案1】:

我相信你可以完成无限的模式。所以很难告诉你所有你正​​在寻找的代码。你应该为自己研究很多技术和“窃取”想法。

据我所见,您正在使用 JavaScript 来执行此模式,但还有其他方法可以完成此操作。例如,您可以简单地使用 HTMLCSS。喜欢:

<!DOCTYPE html>
<html>
<head>
    <style>
        body {
            background-image: url("image.png");
            background-repeat: repeat-y;
        }
    </style>
</head>
<body>
    <h1>The background-repeat Property</h1>
    <p>Here, the background image is repeated only vertically.</p>
</body>
</html>

此外,background-repeat 属性可以具有以下值:

background-repeat: repeat|repeat-x|repeat-y|no-repeat|initial|inherit;

最后还有更多CSS 属性可用于执行不同的背景模式,例如:

background-position: center; /* Center the image */
background-size: cover; /* Resize the background image to cover the entire container */

HTMLCSS 文档: https://www.w3schools.com/cssref/pr_background-repeat.asp

【讨论】:

    猜你喜欢
    • 2015-05-23
    • 2021-04-23
    • 2014-08-09
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多