如何在 Konvajs 中为 Konva.Image() 对象添加纹理?

How to add a texture to a Konva.Image() object in Konvajs?

我已经按照这个post中的答案做了; ,并且运行良好。

有没有办法对 KonvaJS 做同样的事情?

据我所知,KonvaJS 尚不支持创建纹理叠加层所需的合成。但是 Konva.Image 可以将原生 html5 canvas 元素作为其图像源,因此只需在 html5 canvas 元素上进行叠加,然后将其提供给孔瓦:var textureImage = new Konva.Image({ image:myCanvasElement })

示例注释代码和演示:

关于 Microsoft:需要 Edge -- IE 不允许合成

var stage;

// Attributions of code that applies textures using compositing: 
// Indirectly from your SO Q&A: 
// Directly from this SO Q&A: 
// image loading for demo (ignore)
var img1 = new Image;
var img2 = new Image;
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
//
function createCompositedCanvas(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 code


function go() {
  // create stage
  stage = new Konva.Stage({
    container: 'container',
    width: img1.width,
    height: img1.height
  });
  var layer = new Konva.Layer();
  stage.add(layer);
  // create composited canvas
  var canvas = createCompositedCanvas(img1, img2);
  // use the in-memory canvas as an image source for Konva.Image
  var img = new Konva.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;}
<script src="https://cdn.rawgit.com/konvajs/konva/0.9.0/konva.min.js"></script>
<div id="container"></div>
<h4>Native canvas element used to do compositing</h4>