如何将纹理添加到Konvajs中的Konva.Image()对象?

时间:2016-03-19 04:33:02

标签: javascript canvas konvajs

我已经按照这篇文章中的答案; fill image with texture pattern,它运作良好。

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

1 个答案:

答案 0 :(得分:5)

AFAIK,KonvaJS尚不支持创建纹理叠加层所需的合成。但是Konva.Image可以将原生html5 canvas元素作为其图像源,因此只需在html5 canvas元素上进行叠加,然后将其提供给Konva: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: 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 = 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>