我遵循了这篇文章中的答案;用纹理图案填充图像,它工作得很好。
有没有办法对KonvaJS做同样的事情?
AFAIK,KonvaJS 还不支持创建纹理覆盖所需的合成。但是 aKonva.Image
可以将原生 html5 画布元素作为其图像源,因此只需在 html5 画布元素上进行叠加,然后将其提供给 Konva:var textureImage = new Konva.Image({ image:myCanvasElement })
示例注释代码和演示:
关于微软:需要 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>