在Konva中以路径形式显示SVG的渐变样式问题求助
Konva路径形式渲染SVG渐变的问题解决
问题背景
需要以路径形式在Konva中渲染SVG内容,不使用Konva.Image,但渐变样式无法正常生效。
原始SVG代码
<?xml version="1.0" encoding="UTF-8"?> <svg id="Game" xmlns="http://www.w3.org/2000/svg" width="540.1" height="540.1" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 540.1 540.1"> <defs> <linearGradient id="linear-gradient" x1="40" y1="0" x2="40" y2="80" gradientUnits="userSpaceOnUse"> <stop offset="0" stop-color="#fff"/> <stop offset=".2" stop-color="#fbfbfb"/> <stop offset=".3" stop-color="#f2f2f2"/> <stop offset=".5" stop-color="#e1e1e1"/> <stop offset=".6" stop-color="#cacaca"/> <stop offset=".7" stop-color="#acacac"/> <stop offset=".8" stop-color="#888"/> <stop offset=".9" stop-color="#5d5d5d"/> <stop offset="1" stop-color="#333"/> </linearGradient> </defs> <circle id="Player" cx="40" cy="40" r="40" fill="url(#linear-gradient)"/> </svg>
原始Konva代码
var circle = new Konva.Circle({ radius: 40, fillLinearGradientStartPoint: { x: 40, y: 0 }, fillLinearGradientEndPoint: { x: 40, y: 80 }, fillLinearGradientColorStops: [0, '#fff', 0.2, '#fbfbfb', 0.3, '#f2f2f2', 0.5, '#e1e1e1', 0.6, '#cacaca', 0.7, '#acacac', 0.8, '#888', 0.9, '#5d5d5d', 1, '#333'], //gradientUnits:"userSpaceOnUse" scale: { x: 3, y: 3 } })
问题原因
Konva的渐变坐标默认采用元素本地坐标系(以元素自身原点为基准),而SVG中使用的gradientUnits="userSpaceOnUse"是基于画布全局坐标系。加上代码中给Circle设置了scale: {x:3,y:3},渐变坐标未适配缩放比例,导致渐变错位失效。
解决方案
方案1:适配缩放比例转换坐标
将SVG的全局坐标按缩放比例反向换算,转为元素本地坐标:
var circle = new Konva.Circle({ radius: 40, // 全局坐标除以缩放比例3,转为元素本地坐标 fillLinearGradientStartPoint: { x: 40/3, y: 0/3 }, fillLinearGradientEndPoint: { x: 40/3, y: 80/3 }, fillLinearGradientColorStops: [0, '#fff', 0.2, '#fbfbfb', 0.3, '#f2f2f2', 0.5, '#e1e1e1', 0.6, '#cacaca', 0.7, '#acacac', 0.8, '#888', 0.9, '#5d5d5d', 1, '#333'], scale: { x: 3, y: 3 } })
方案2:使用元素相对位置定义渐变
直接基于元素自身尺寸设置渐变起点终点,无需依赖全局坐标:
var circle = new Konva.Circle({ radius: 40, // 以元素中心为原点,从顶部(y=-radius)到底部(y=radius) fillLinearGradientStartPoint: { x: 0, y: -40 }, fillLinearGradientEndPoint: { x: 0, y: 40 }, fillLinearGradientColorStops: [0, '#fff', 0.2, '#fbfbfb', 0.3, '#f2f2f2', 0.5, '#e1e1e1', 0.6, '#cacaca', 0.7, '#acacac', 0.8, '#888', 0.9, '#5d5d5d', 1, '#333'], scale: { x: 3, y: 3 } })
内容的提问来源于stack exchange,提问作者Meysam Ghorbani
相关产品推荐
相关产品推荐

