You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用vue-konva时fillPatternImage无法生效的问题求助

解决vue-konva中fillPatternImage不生效的问题

问题原因分析

你的代码存在两个关键问题导致fillPatternImage无法生效:

  1. 无效的图片URL:使用的https://example.com/image.jpg是占位地址,实际无法加载到有效图片,导致fillPatternImage始终为null。
  2. 冲突的fill属性:同时设置了fill: 'red'和fillPatternImage,Konva会优先使用纯色填充,覆盖图片图案。

修正后的代码

脚本部分

// App.vue script
const loadImage = function (imgSrc) {
  return new Promise((resolve, reject) => {
    const image = new window.Image();
    image.src = imgSrc;
    image.onload = () => {
      resolve(image);
    };
    image.onerror = (err) => {
      console.error('图片加载失败:', err);
      reject(err);
    };
  });
};

export default {
  data() {
    return {
      showStage: false,
      configKonva: {
        width: window.innerWidth,
        height: window.innerHeight,
      },
      configCircle: {
        x: 100,
        y: 100,
        radius: 70,
        // 移除fill属性,避免覆盖图案填充
        fillPatternImage: null,
        fillPatternRepeat: 'repeat',
      },
    };
  },

  created() {
    // 使用可访问的测试图片地址
    loadImage('https://picsum.photos/200/200')
      .then((img) => {
        this.configCircle.fillPatternImage = img;
        this.showStage = true;
      })
      .catch(err => console.error('处理图片加载错误:', err));
  },
};

模板部分

<!-- App.vue template -->
<div id="app">
  <v-stage v-if="showStage" :config="configKonva">
    <v-layer>
      <v-circle :config="configCircle"></v-circle>
    </v-layer>
  </v-stage>
</div>

额外说明

  • 确保使用的图片URL可以正常访问,若图片来自外部域名,需服务器配置CORS避免跨域问题。
  • 若需要保留fill属性作为加载失败的 fallback,可在图片加载完成后将fill设置为null或undefined。

内容的提问来源于stack exchange,提问作者Paulo R.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 18:03:23