HTML5 Canvas繪圖基礎


一、canvas是什么?

canvas就是畫布

canvas元素用於在網頁上繪制2D圖形和圖像

二、canvas坐標體系

canvas的默認寬高是300*150,要在腳本中對畫布進行操作。

踩坑注意:如果要對canvas畫布的大小進行操作,不能在style上操作,要在內聯樣式上寫或者js中操作,在style上改變寬高畫布會被拉伸

三、canvas畫直線、曲線和圓

(1)canvas畫直線

<canvas id="myCanvas1">
    您的瀏覽器不支持Canvas,請升級瀏覽器
  </canvas>
<script>
    var canvas1 = document.getElementById('myCanvas1');
    var ctx1 = canvas1.getContext('2d');  //
    ctx1.canvas.width = 100; //js獲取寬高
    ctx1.canvas.height = 100;
    ctx1.moveTo(0, 0);   //起點
    ctx1.lineTo(100, 100);  //直線到100,100
    ctx1.stroke(); //沒有這個stroke()的話不會出現畫布效果
</script>

(2)canvas畫圓和矩形

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
     ctx.canvas.width = 600;
     ctx.canvas.height = 400;
     ctx.beginPath(); //重新開始新路徑
     ctx.moveTo(0, 0);
     ctx.lineTo(100, 100);
     ctx.lineTo(100, 200);
     ctx.closePath(); //閉合路徑(可以連接首尾)
     ctx.stroke(); //記得最后調用stroke才能畫線
     // 畫圓
     ctx.beginPath();
     //ctx.arc(開始原點x,開始原點y,半徑,起始弧度,終止弧度,true表示逆時針動畫)
     ctx.arc(200, 150, 100, 0, Math.PI * 2, true);
     ctx.closePath();
     ctx.stroke();
     //畫矩形,封裝一個stroke的rect(矩形,所以不用調用rect)
     //ctx.strokeRect(開始原點x,開始原點y,寬度,高度)
     ctx.strokeRect(100, 100, 100, 100);

(3)canvas描邊和填充

//線條樣式
    ctx.beginPath();
    ctx.strokeStyle = "#00FF00"; //設置線條的樣式顏色
    ctx.lineWidth = 5; //設置描邊的線寬
    ctx.moveTo(100, 200);
    ctx.lineTo(200, 200);
    ctx.stroke();
    //填充
    ctx.beginPath();
    ctx.moveTo(300, 100);
    ctx.lineTo(400, 100);
    ctx.lineTo(400, 200);
    ctx.closePath();
    //ctx.stroke();
    ctx.fillStyle = "#0000FF"; //設置填充的顏色
    ctx.fill(); //填充 (如果是首尾沒有連接的話會自動連接填充里面)
    ctx.beginPath();
    ctx.moveTo(300, 150);
    ctx.lineTo(400, 150);
    ctx.lineTo(400, 250);
    ctx.closePath();
    ctx.stroke();

四、canvas圖形變換

(1)、save()和restore()方法

save(),保存當前繪畫環境,包括樣式和變換

restroe(),恢復當前繪畫環境,包括樣式和變換

注意:ctx.save()和restore()方法,保存了上下文的環境包括圖形變換和樣式。並且一定要同時出現。restore之后的canvas樣式會以save之前的樣式重新開始

 ctx.beginPath();
    //ctx.save()和restore()方法,保存了上下文的環境包括圖形變換和樣式。並且一定要同時出現
    ctx.save();
    //x軸的平移方向,translate平移變換
      ctx.translate(0, 20);
      ctx.moveTo(50, 50);
      ctx.lineTo(150, 50);
    ctx.restore(); //restore之后的canvas樣式會以save之前的樣式重新開始
    ctx.stroke();
    //ctx.fillRect(-5, -5, 10, 10);
    ctx.beginPath();

(2)偏移、旋轉、縮放變換

ctx.beginPath();
    //x軸的平移方向,translate平移變換
    ctx.translate(300, 0);
    for(var i=0; i<10; i++) {
    //rotate旋轉變換,Math.PI=180
      ctx.rotate(Math.PI / 5);
      ctx.moveTo(-50, 0);
      ctx.lineTo(50, 0);
    }
    ctx.stroke();
    //scale縮放變換,(x軸縮放,y軸縮放)
    ctx.sacle(1,0.5)

 五、canvas中的漸變

(1)線性漸變 ctx.createLinearGradient(x軸起點,y軸起點,x軸終點,y軸終點)

(2)徑向漸變 ctx.createRadialGradient(x,y起點,原點起點,x,y終點,原點終點)

(3)漸變中的顏色轉換ctx.createLinearGradient(createRadialGradient).addColorStop(0-1百分比,rgba)

var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    ctx.canvas.width = 600;
    ctx.canvas.height = 400;
    //線性漸變 ctx.createLinearGradient(x軸起點,y軸起點,x軸終點,y軸終點);
    var linearGradient = ctx.createLinearGradient(50, 50, 150, 150);
    //linearGradient.addColorStop(0-1百分比,rgba)
    linearGradient.addColorStop(0, 'rgb(255,0,0)');
    linearGradient.addColorStop(0.5, 'rgb(0,255,0)');
    linearGradient.addColorStop(1, 'rgb(0,0,255)');
    ctx.fillStyle = linearGradient;
    ctx.fillRect(0, 0, 200, 200);
    ctx.beginPath();
    ctx.arc(400, 150, 100, 0, Math.PI * 2, true);
    ctx.closePath();
    //徑向漸變 ctx.createRadialGradient(x,y起點,原點起點,x,y終點,原點終點)
    var radialGradient = ctx.createRadialGradient(400, 150, 0, 400, 150, 100);
    radialGradient.addColorStop(0, 'rgb(255,0,0)');
    radialGradient.addColorStop(1, 'rgb(0,0,255)');
    ctx.fillStyle = radialGradient;
    ctx.fill();

六、canvas中文字和圖片的繪制

1、canvas中的文字

var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    ctx.canvas.width = 600;
    ctx.canvas.height = 400;
    var str = "hello world"
    //設置文本樣式、比如大小,字體
    ctx.font = "bold 100px sans-serif";
    //水平對齊設置,left,center,top
    ctx.textAlign = "center";
    //垂直對齊設置,top,middle,bottom
    ctx.textBaseline = "top";
    ctx.fillStyle = "#FF0000";
    //填充文本
    ctx.fillText(str, 300, 100);
    ctx.strokeStyle = "#0000FF";
    //描邊文本
    ctx.strokeText(str, 300, 300);
    //獲取文本寬度
    console.log(ctx.measureText("慕課網").width);

2、canvas圖片的繪制(圖片的裁剪:要看圖片的實際寬高)

注意:一定要在圖像加載完成后的回調中會繪制圖像,否則圖像顯示不出來

 var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    ctx.canvas.width = 600;
    ctx.canvas.height = 400;
    ctx.fillStyle = "#000000";
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    var img = new Image();
    img.src = "logo.png";
    //一定要在圖像加載完成后的回調中會繪制圖像,否則圖像顯示不出來
    img.onload = function () {
      //如果是三個參數,表示以(0,0)在圖像左上角開始繪制圖像
      //如果是五個參數,表示在(0,0)點處繪制img圖像,縮放(截取)成40*40
      //如果是九個參數,表示獲取img圖像(0,0)點處的40*40區域,繪制在(100,100)點處,縮放成80*80
      ctx.drawImage(img, 0, 0, 40, 40, 100, 100, 80, 80);

3、圖形畫刷

var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    var img = new Image();
    img.src = "logo.png";
    img.onload = function () {
      //創建圖形畫刷,repeat,no-repeat,repeat-x,repeat-y
      var pattern = ctx.createPattern(img, "repeat");
      ctx.fillStyle = pattern;
      ctx.fillRect(0, 0,canvas.width,canvas.height);

七、canvas中剪輯、陰影以及曲線的繪制

 1、canvas中剪輯區域

var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    //保存當前環境
    ctx.save();
    ctx.beginPath();
    ctx.arc(200, 150, 100, 0, Math.PI * 2, true);
    ctx.closePath();
    //進行區域剪輯
    ctx.clip();
    //恢復環境,釋放了剪輯區域的作用
    ctx.restore();
    ctx.fillStyle = "#FF0000";
    ctx.fillRect(100, 100, 200, 200);
    ctx.fillStyle = "#0000FF";
    ctx.fillRect(200, 150, 200, 200);

2、canvas陰影繪制

//陰影的x軸偏移量
    ctx.shadowOffsetX = 10;
    //陰影的y軸偏移量
    ctx.shadowOffsetY = 10;
    //陰影的顏色
    ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
    //陰影的模糊程度
    ctx.shadowBlur = 1.5;
    ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
    ctx.fillRect(100, 100, 100, 100);

3、canvas繪制曲線

ctx.beginPath();
    ctx.arc(150, 150, 100, 0, Math.PI, true);
    ctx.stroke();
    // 二次樣條曲線
    ctx.beginPath();
    ctx.moveTo(50, 350); //起始點 
    ctx.quadraticCurveTo(100, 250, 150, 350); // 前兩個參數是可以調節的點,最后兩個參數是終點
    ctx.stroke();
    showPoint(ctx, 50, 350);
    showPoint(ctx, 100, 250);
    showPoint(ctx, 150, 350);
    // 三次貝塞爾曲線
    ctx.beginPath();
    ctx.moveTo(200, 350);
    ctx.bezierCurveTo(200, 250, 300, 250, 300, 350); // 前四個參數是可以調節的點,最后兩個參數是終點
    ctx.stroke();
    ctx.fill();
    showPoint(ctx, 200, 350);
    showPoint(ctx, 200, 250);
    showPoint(ctx, 300, 250);
    showPoint(ctx, 300, 350);

八、canvas動畫(實現一個方塊左右移動,鼠標放上去就停止的效果)

var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    ctx.canvas.width = 600;
    ctx.canvas.height = 400;
    var posx = 0, posy = 0;
    var dir = 1; //判斷方塊是正向前進還是反向運動。正向就是1,反向就是-1
    var isMouseInReat //判斷鼠標是否移動進了方塊里面,是的話就停止運動
    canvas.onmousemove =function(e){
      var mouseX = e.offsetX;
      var mouseY = e.offsetY;
      if (mouseX>posx && mouseX<posx +50 && mouseY>posy && mouseY<posy +50){
        isMouseInReat = true;
      }else{
        isMouseInReat = false;
      }
    }
    setInterval(function() {
      if(!isMouseInReat){
        posx = posx + 10 * dir;
      }
      //clearRect清空畫布的一個矩形區域
      ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
      ctx.fillRect(posx, posy, 50, 50);
      if (posx +50 >=ctx.canvas.width) {
        dir = -1;
      }else if(posx <= 0){
        dir = 1
      }
    }, 50);

九、canvas離屏技術(可以解決因為setInterval多次循環卡頓的問題)

// 要顯示的canvas
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    ctx.canvas.width = 600;
    ctx.canvas.height = 400;
    // 不顯示的canvas(離屏)用dispaly:none隱藏即可
    var offCanvas = document.getElementById('offCanvas');
    var offCtx = offCanvas.getContext('2d');
    offCtx.canvas.width = 600;
    offCtx.canvas.height = 400;
    
    ctx.fillStyle = "#FF0000";
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    offCtx.strokeStyle = "#00FF00";
    offCtx.lineWidth = 10;
    offCtx.moveTo(0, 0);
    offCtx.lineTo(offCtx.canvas.width, offCtx.canvas.height);
    offCtx.stroke();
    
    // 把離屏canvas的內容搬過來
    ctx.drawImage(offCanvas, 0, 0, ctx.canvas.width, ctx.canvas.height,
                  0, 0, offCtx.canvas.width, offCtx.canvas.height);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM