HTML5 Canvas API 之 CanvasRenderingContext2D
1.属性
-
canvas 对与给定上下文关联的HTMLCanvasElement对象的只读引用
<canvas id="canvas"></canvas> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.canvas; // <canvas id="canvas"></canvas>
-
fillStyle 描述颜色和样式的属性 color | gradient | pattern
-
strokeStyle 画笔(绘制图形)颜色。默认 balck || #000
// color ctx.fillStyle = "#333333"; ctx.fillStyle = "red"; ctx.fillStyle = "rgb(0, 0, 0)"; ctx.fillStyle = "rgba(0, 0, 0, 0.3)"; // gradient var grd = ctx.createLinearGradient(0, 0, 80, 0); // 设置线性渐变规则 grd.addColorStop(0, "black"); grd.addColorStop(0.5, "white"); grd.addColorStop(1, "black"); // 渐变范围 0 - 1 ctx.fillStyle = grd; ctx.fillRect(10, 10, 100, 100);
ctx.createLinearGradient(0, 80, 80, 0)
ctx.createLinearGradient(0, 0, 80, 80)
ctx.createLinearGradient(0, 0, 80, 0)// pattern 元素可以是图片、视频,或者其他 <canvas> 元素 var img = new Image(); img.src = "img/test2.jpg"; img.onload = function(){ var pat = ctx.createPattern(img, "repeat"); // repeat|repeat-x|repeat-y|no-repeat ctx.lineWidth = 30; ctx.strokeStyle = pat; ctx.arc(150, 150, 100, 0, 2 * Math.PI, false); ctx.stroke(); ctx.closePath(); // ctx.fillStyle = pat; // ctx.fillRect(0, 0, 100, 100); // ctx.fill(); }
ctx.arc(100, 100, 80, 0, 2 * Math.PI, false);
ctx.fillRect(0, 0, 100, 100); -
font 符合CSS font 语法的DOMString 字符串。默认字体是 10px sans-serif。
ctx.font = "bold 48px serif"; ctx.strokeText("Hello world", 50, 100); // 加载自定义字体 var fot = new FontFace('testFont', 'url(x)'); fot.load().then(function() { ctx.font = "14px testFont"; }