javascript - Fill image with texture/pattern - Stack Overflow
Fill image with texture/pattern
I'm looking for a solution to change the texture/pattern for a product. At this moment i have: A .png picture of a couch with a transparent background A .png picture of a texture With the foll...
stackoverflow.com
var img1 = new Image, img2 = new Image, cnt = 2, canvas = document.getElementById("canvas"), ctx = canvas.getContext("2d");// image loading for demo (ignore)img1.xxxxonload = img2.xxxxonload = function() {if (!--cnt) go()};img1.src = "//i.imgur.com/8WqH9v4.png"; // sofaimg2.src = "//i.stack.imgur.com/sQlu8.png"; // pattern// MAIN CODE ---function go() { // create a pattern ctx.fillStyle = ctx.createPattern(img2, "repeat"); // fill canvas with pattern ctx.fillRect(0, 0, canvas.width, canvas.height); // use blending mode multiply ctx.globalCompositeOperation = "multiply"; // draw sofa on top ctx.drawImage(img1, 0, 0, img1.width*.5, img1.height*.5); // change composition mode ctx.globalCompositeOperation = "destination-in"; // draw to cut-out sofa ctx.drawImage(img1, 0, 0, img1.width*.5, img1.height*.5);}