代码片段
wxml
js
代码中定义了三组色彩,blue/yellow/red, 开发环境绘制正常,真机只有两种
const query = wx.createSelectorQuery()
query.select('#canvas')
.fields({
node: true,
size: true
})
.exec((res) => {
const canvas = res[0].node
canvas.width = 20;
canvas.height = 256;
let ctx = canvas.getContext("2d");
const colorStops = {
0: "blue",
0.5: "yellow",
1: "red",
};
// 创建线性渐变色
let linearGradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
console.log(colorStops);
for (const key in colorStops) {
linearGradient.addColorStop(key, colorStops[key]);
}
// 绘制渐变色条
ctx.fillStyle = linearGradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
})
安卓 和 苹果 的真机都不行
@是柿子啊
应该是添加 ColorStop 顺序不对
onReady 内容改成如下即可:
Page({ onReady: function () { const query = wx.createSelectorQuery() query.select('#canvas') .fields({ node: true, size: true }) .exec((res) => { const canvas = res[0].node canvas.width = 20; canvas.height = 256; let ctx = canvas.getContext("2d"); // 原来是一个对象,用 for-in 遍历顺序是 0、1、0.5,添加顺序不对,改成数组后顺序就固定了 const colorStops = [ [0, "blue"], [0.5, "yellow"], [1, "red"], ]; // 创建线性渐变色 let linearGradient = ctx.createLinearGradient(0, 0, 0, canvas.height); console.log(colorStops); colorStops.forEach(([pos, color]) => { linearGradient.addColorStop(pos, color); }) // 绘制渐变色条 ctx.fillStyle = linearGradient; ctx.fillRect(0, 0, canvas.width, canvas.height); }) }, })
https://developers.weixin.qq.com/s/0YUqRimW7cAH
已创建代码片段