1. 程式人生 > >canvas給圖形添加顏色

canvas給圖形添加顏色

com ont tex lob ora getc ons rect lock

canvas給圖形添加顏色

  1. 合法屬性

    ctx.fillStyle = ‘orange‘;
    ctx.fillStyle = ‘#FFA500‘;
    ctx.fillStyle = ‘rgb(255, 165, 0)‘;
    ctx.fillStyle = ‘rgba(255, 165, 0, 1)‘;
    
    strokeStyle類似
    
    ctx.globalAlpha = 0.2; 設置全局透明度
  2. 給圖形上色

    技術分享圖片

    const canvas = document.getElementById(‘canvas‘);
    const ctx = canvas.getContext(‘2d‘);
    
    ctx.fillStyle=‘orange‘;
    ctx.fillRect(25, 25, 100, 100);
    
    ctx.fillStyle=‘blue‘;
    ctx.fillRect(125, 25, 100, 100);
    
    ctx.fillStyle=‘green‘;
    ctx.fillRect(25, 125, 100, 100);
    
    ctx.fillStyle=‘red‘;
    ctx.fillRect(125, 125, 100, 100);
  3. 給圖形邊框上色

    技術分享圖片

    ctx.strokeStyle=‘rgb(255, 165, 0)‘;
    ctx.beginPath();
    ctx.arc(200, 200, 50, 0, (Math.PI/180)*360, true);
    ctx.stroke();
  4. 繪制半透明圖形

    技術分享圖片

    ctx.fillStyle=‘rgb(255, 165, 0)‘;
    ctx.beginPath();
    ctx.arc(200, 200, 50, 0, (Math.PI/180)*360, true);
    ctx.fill();
    
    ctx.globalAlpha = 0.2;
    
    ctx.fillStyle=‘white‘
    ctx.beginPath();
    ctx.arc(200, 200, 10, 0, Math.PI * 2, true);
    ctx.fill();
    
    ctx.beginPath();
    ctx.arc(200, 200, 20, 0, Math.PI * 2, true);
    ctx.fill();
    
    ctx.beginPath();
    ctx.arc(200, 200, 30, 0, Math.PI * 2, true);
    ctx.fill();

canvas給圖形添加顏色