简体   繁体   中英

How to change image repeat pattern in HTML5 Canvas

I am trying to create many different image repeat pattern . I used the following code for the repeat pattern. The code is working fine for regular patterns but I need many different sets of the pattern as the image is shown below.

在此处输入图片说明

OR Like below...

在此处输入图片说明

But with the below code I have this pattern only that is here .... 在此处输入图片说明

<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>

Please help in this that how I can get that different patterns. Thanks in Advance.

I believe that there are infinite patterns you can accomplish. So it's difficult to tell you all the code that you are looking for. You should research a lot of tecniques and "steal" ideas for yourself.

From what I saw you are using JavaScript to perform this patterns, but there are other ways to accomplish this. You can simply use HTML and CSS for example. Like:

<!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>

Also, the background-repeat property can have the following values:

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

For last there are more CSS properties you can use to perform different background patterns, like:

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

HTML and CSS documentation: https://www.w3schools.com/cssref/pr_background-repeat.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM