<canvas id="canvas"></canvas> <script> const canvas = document.querySelector('#canvas') const context = canvas.getContext('2d', {willReadFrequently: true}) const CANVAS_WIDTH = canvas.width = canvas.clientWidth const CANVAS_HEIGHT = canvas.height = canvas.clientHeight // 创建渐变 let g = context.createLinearGradient(0, 0, CANVAS_WIDTH, 0) // 设置渐变 g.addColorStop(0, '#00cc00') g.addColorStop(0.5, '#ffff00') g.addColorStop(1, '#ff0000') // 填充样式 context.fillStyle = g // 绘制渐变矩形 context.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT) // 获取线性渐变某个位置(范围0-1)的点的颜色 function getCanvasPointColor(pos) { pos = pos * (CANVAS_WIDTH - 1) let imageData = context.getImageData(pos, 0, 1, 1); let pixel = imageData.data; let r = pixel[0] let g = pixel[1] let b = pixel[2] return`rgb(${r},${g},${b})` } </script>