學習canvas 過程當中的幾點總結

1.canvas的畫布大小與canvas元素大小

canvas尺寸分爲兩種,一種是canvas元素自己的尺寸,另外一種是canvas畫布的尺寸canvas

  • canvas自己尺寸能夠經過style樣式來設置瀏覽器

    .canvas{
        width:100px;
        height:100px;
    }
    /* 設置了元素在瀏覽器能夠看見的尺寸 */
  • canvas畫布尺寸經過元素widthheight兩個屬性設置,也能夠經過js給畫布設置尺寸。默認尺寸爲300*150spa

    <canvas width="100" height="100"></canvas>

    或者code

    var canvas=document.getElementById("canvas");
    canvas.width = 100;
    canvas.height = 100;

    若是兩個尺寸不一致,那麼畫出來的圖形,和想象中的圖形是有差距的。對象

2.扇形漸變的規律

扇形漸變的語法:blog

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.createRadialGradient(x1, y1, r1, x2, y2, r2);
// 建立一個從以(x1, y1)點爲圓心、r1爲半徑的圓到以(x2, y2)點爲圓心、r2爲半徑的圓的徑向漸變對象

漸變規律能夠分爲兩種狀況:圖片

  • 兩個圓同圓心,或者兩個圓屬於包含關係get

    漸變從一個圓的圓周向另外一個圓的圓周輻射漸變it

    // 包含
    var grb = ctx.createRadialGradient(245,175,20,285,175,75);
    grb.addColorStop(0, "red");
    grb.addColorStop(0.5, "green");
    grb.addColorStop(1, "yellow");
    ctx.fillStyle = grb;
    
    ctx.fillRect(210,100,150,150);

    效果以下圖的包含關係:class

    圖片描述

  • 相交或相離

    在兩個圓的切線與圓周組成範圍內,從開始圓的圓周向結束圓的圓周漸變

    // 相交
    grb = ctx.createRadialGradient(440,175,75,520,175,50);
    grb.addColorStop(0, "red");
    grb.addColorStop(0.5, "green");
    grb.addColorStop(1, "yellow");
    ctx.fillStyle = grb;
    
    ctx.fillRect(380,100,200,150);
    
    // 相離
    grb = ctx.createRadialGradient(675,175,75,900,175,50);
    grb.addColorStop(0, "red");
    grb.addColorStop(0.5, "green");
    grb.addColorStop(1, "yellow");
    ctx.fillStyle = grb;
    
    ctx.fillRect(600,100,300,150);

    效果如上圖的相交和相離,在切線與圓周組成的範圍內漸變

相關文章
相關標籤/搜索