HTML5 canvas

Canvas

Canvas 是HTML5新增的組件,它就是一塊畫(huà)布,可以用JavaScript在上繪制各種圖標(biāo)、動(dòng)畫(huà)等。

Web頁(yè)面增加畫(huà)布

Canvas元素是一個(gè)標(biāo)準(zhǔn)的HTML5元素,可以直接在HTML5頁(yè)面中添加<canvas>標(biāo)簽,如

<!DOCTYPE HTML>
<html>
<head>
     <title>Look what I Drew</title> 
    <meta charset="utf-8">
</head>
<body> 
      <canvas id="draw" width="600" height="200"></canvas>
</body>
</html>

width屬性定義它在web頁(yè)面中水平方向所占的像素,Height定義了它在web頁(yè)面中垂直方向所占元素。
注意:上面的web頁(yè)面無(wú)法顯示畫(huà)布的,除非你在畫(huà)布上繪制了內(nèi)容。
需要在<canvas>上調(diào)用getContext(),并提供一個(gè)‘2d’參數(shù)

畫(huà)布的一些圖形API

繪制矩形
1. CanvasRenderingContext2D.clearRect()
設(shè)置指定矩形區(qū)域內(nèi)(以點(diǎn)(x,y)為起點(diǎn),范圍是(width,height)所有像素變成透明,并擦除之前繪制的所有內(nèi)容);

2.CanvasRenderingContext2D.fillRect()  繪制帶填充色的矩形
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(10, 10, 100, 100);

3.CanvasRenderingContext2D.strokeRect() 可以繪制有顏色邊框的矩形

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.strokeStyle = "green";
ctx.strokeRect(10, 10, 100, 100);

4. CanRenderingContext2D.rect() 繪制矩形
使用fill()或者 stroke()方法填充或者描邊
fillRect
strokeRect
繪制圓形
CanvasRenderingContext2D.arc()
void ctx.arc(x,y,radius,startAngle,endAngle,anticlockwise);
最后一個(gè)參數(shù)是可選Boolean值,如果為true,則逆時(shí)針繪制圓??;


ctx.beginPath();
ctx.arc(75, 75, 50, 0, 2 * Math.PI,false);
ctx.stroke();

繪制線

  • beginPath方法告訴畫(huà)布開(kāi)始一個(gè)新路徑
    *moveTo 方法把畫(huà)筆移到畫(huà)布上的指定點(diǎn)
    *line To 方法描繪路徑,從畫(huà)筆的當(dāng)前位置描繪到畫(huà)布上的另一個(gè)點(diǎn)
    *closePath 方法將路徑的起始點(diǎn)連接到當(dāng)前路徑的最后一個(gè)點(diǎn)
//繪制線
var canvas = document.getElementById("canvas");
var ctx = convas.getContext("2d");

ctx.beginPath();
ctx.strokeStyle = "cyan";
ctx.moveTo(20,20);
ctx.lineTo(200,20);
ctx.stroke();

繪制圖片

void*ctx*.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

parameter
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容