canvas扇形径向渐变和角度渐变

径向渐变

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

var centerX = canvas.width / 2; // 扇形中心点的X坐标
var centerY = canvas.height / 2; // 扇形中心点的Y坐标
var radius = 100; // 扇形的半径
var startAngle = 0; // 扇形的起始角度
var endAngle = Math.PI / 2; // 扇形的结束角度

var gradient = context.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius);
gradient.addColorStop(0, 'rgba(0, 0, 0, 0)'); // 渐变的起始颜色为完全透明
gradient.addColorStop(1, 'rgba(0, 0, 0, 1)'); // 渐变的结束颜色为完全不透明

context.beginPath();
context.moveTo(centerX, centerY);
context.arc(centerX, centerY, radius, startAngle, endAngle);
context.fillStyle = gradient; // 设置扇形的填充样式为渐变
context.fill();

扇形渐变

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

// var width = canvas.width,height=canvas.height;
// if (window.devicePixelRatio) {
//   console.log('window.devicePixelRatio', window.devicePixelRatio)
//   devicePixelRatio = window.devicePixelRatio;
//     canvas.style.width = width + "px";
//     canvas.style.height = height + "px";
//     canvas.height = height * devicePixelRatio;
//     canvas.width = width * devicePixelRatio;
//     context.scale(devicePixelRatio, devicePixelRatio);
// }

var centerX = canvas.width / 2; // 扇形中心点的X坐标
var centerY = canvas.height / 2; // 扇形中心点的Y坐标
var radius = 100; // 扇形的半径

function draw() {
  // context.scale(0.25, 0.25);
    for(let i = 0; i < 90; i+=1) {
      // 绘制扇形
      context.beginPath();
      context.moveTo(centerX, centerY);
      context.arc(centerX, centerY, radius, toRadian(i), toRadian(i+1));
      context.fillStyle = 'rgba(255, 0, 0, ' + i/90 + ')'; // 根据透明度设置填充样式
      context.fill();
    }
}

// 开始动画
draw();

function hexToRgb(hex) {
  return 'rgb(' + parseInt('0x' + hex.slice(1, 3)) + ',' + parseInt('0x' + hex.slice(3, 5))
          + ',' + parseInt('0x' + hex.slice(5, 7)) + ')';
}


function toRadian(angle) {
  return Math.PI / 180 * angle;
}

 

posted @ 2023-06-12 15:46  古墩古墩  Views(342)  Comments(0)    收藏  举报