我从Konva开始,我想知道是否可以在复杂的svg中使用png作为剪切区域。
我有一个mask image(在透明背景上必须为白色)和一个texture。我想用纹理图像like this替换白色形状。
我设法编写了一个脚本,该脚本可以用原始js(在vue组件中)完成我想要的工作:
<template>
<div>
<h1>Fill a png image with a texture</h1>
<canvas ref="canvas" id="canvas" width="800" height="500">
Canvas not supported on your browser
</canvas>
</div>
</template>
<script>
export default {
name: 'fillPng',
data() {
return {
imageSrc: '/static/static/assets/fillPng/patternMaskPicture.png',
textureSrc: '/static/static/assets/fillPng/texture.png',
imageLoaded: false,
textureLoaded: false,
image: null,
texture: null,
};
},
computed: {
canvas() {
return this.$refs.canvas;
},
context() {
this.$log.debug('canvas =', this.canvas);
this.$log.debug('context =', this.canvas.getContext('2d'));
return this.canvas.getContext('2d');
},
},
methods: {
go() {
if (!this.imageLoaded || !this.textureLoaded) {
return;
}
this.context.fillStyle = this.context.createPattern(this.texture, 'repeat');
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.context.globalCompositeOperation = 'multiply';
this.context.drawImage(this.image, 0, 0, this.canvas.width, this.canvas.height);
this.context.globalCompositeOperation = 'destination-in';
this.context.drawImage(this.image, 0, 0, this.image.width, this.image.height);
},
},
mounted() {
this.image = new Image();
this.texture = new Image();
this.image.onload = () => {
this.imageLoaded = true;
this.go();
};
this.texture.onload = () => {
this.textureLoaded = true;
this.go();
};
this.image.src = this.imageSrc;
this.texture.src = this.textureSrc;
},
};
</script>
但是还没有找到使用Konva的方法,或者在更复杂的svg(包含图层,组和其他元素)中使用此脚本。
我找不到一种方法来访问<canvas>
标记来调用getContext('
d')
方法,也找不到一种CanvasRenderingContext2D
对象来调用createPattern
...