Skip to content Skip to sidebar Skip to footer

How To Add A Texture To A Konva.image() Object In Konvajs?

I have followed the answer in this post; fill image with texture pattern, and it is working perfectly. Is there a way to do the same with KonvaJS?

Solution 1:

AFAIK, KonvaJS does not yet support the compositing required to create your texture overlay. But a Konva.Image can take a native html5 canvas element as its image source, so just do your overlay on an html5 canvas element and then feed it to Konva: var textureImage = new Konva.Image({ image:myCanvasElement })

Example annotated code and a Demo:

About Microsoft: Requires Edge -- IE doesn't allow compositing

var stage;

// Attributions of code that applies textures using compositing: // Indirectly from your SO Q&A: http://stackoverflow.com/questions/36097859/add-texture-to-image-object-in-konvajs// Directly from this SO Q&A: http://stackoverflow.com/questions/28545747/fill-image-with-texture-pattern/28552076#28552076// image loading for demo (ignore)var img1 = newImage;
var img2 = newImage;
var cnt = 2;
img1.onload = img2.onload = function() {
  if (!--cnt) go()
};
img1.src = "http://i.imgur.com/8WqH9v4.png"; // sofa
img2.src = "http://i.stack.imgur.com/sQlu8.png"; // pattern//functioncreateCompositedCanvas(img1, img2) {
    // create canvas
    canvas = document.createElement("canvas"),
      ctx = canvas.getContext("2d");
    canvas.width = img1.width;
    canvas.height = img1.height;
    // 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 (blending mode is automatically set to normal)
    ctx.globalCompositeOperation = "destination-in";
    // draw to cut-out sofa
    ctx.drawImage(img1, 0, 0, img1.width * .5, img1.height * .5);
    //document.body.appendChild(canvas);
    return (canvas);
  }
  // end attibuted codefunctiongo() {
  // create stage
  stage = newKonva.Stage({
    container: 'container',
    width: img1.width,
    height: img1.height
  });
  var layer = newKonva.Layer();
  stage.add(layer);
  // create composited canvasvar canvas = createCompositedCanvas(img1, img2);
  // use the in-memory canvas as an image source for Konva.Imagevar img = newKonva.Image({
    x: -200,
    y: -50,
    image: canvas,
    draggable: true
  });
  layer.add(img);
  layer.draw();
}
body{padding:20px;}
#container{
  border:solid 1px#ccc;
  margin-top: 10px;
}
canvas{border:solid 1px red;}
<scriptsrc="https://cdn.rawgit.com/konvajs/konva/0.9.0/konva.min.js"></script><divid="container"></div><h4>Native canvas element used to do compositing</h4>

Post a Comment for "How To Add A Texture To A Konva.image() Object In Konvajs?"