Canvas样本代码
后续代码片段以该例子为模板:
<html>
<body>
<canvas width="800" height="600" id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas");
var c = canvas.getContext("2d");
c.fillStyle = "red";
c.fillRect(100, 100, 400, 300);
</script>
</body>
</html>
矩形
核心代码:
ctx.fillStyle = "red";
//x, y, width, height
ctx.fillRect(20,30,40,50);
效果:
三角形
c.fillStyle = '#ccddff';
c.beginPath();
c.moveTo(50,20);
c.lineTo(200,50);
c.lineTo(150,80);
c.closePath();
c.fill();
c.strokeStyle = 'rgb(0,128,0)';
c.lineWidth = 5;
c.stroke();
效果:
路径
c.fillStyle = 'red';
c.beginPath();
c.moveTo(10,30);
c.bezierCurveTo(50,90,159,-30,200,30);
c.lineTo(200,90);
c.lineTo(10,90);
c.closePath();
c.fill();
c.lineWidth = 4;
c.strokeStyle = 'black';
c.stroke();
效果:
图片(TODO)
img.addEventListener("load", (e) => {
// ctx.drawImage(img, 33, 71, 104, 124, 21, 20, 87, 104);
ctx.drawImage(img, 0, 0); //normal drawing
ctx.drawImage(
img, //draw stretched
0,
0,
266,
266, //source (x,y,w,h)
300,
0,
200,
200 //destination (x,y,w,h)
);
ctx.drawImage(
img, //draw a slice
20,
30,
100,
100, //source coords (x,y,w,h)
550,
0,
250,
50 //destination coords (x,y,w,h)
);
});
效果:
文本
ctx.fillStyle = "black";
ctx.font = "italic "+96+"pt Arial ";
ctx.fillText("this is text", 20,150);
效果:
渐变
var grad = ctx.createLinearGradient(0,0,200,0);
grad.addColorStop(0, "white");
grad.addColorStop(0.5, "red");
grad.addColorStop(1, "black");
ctx.fillStyle = grad;
ctx.fillRect(0,0,400,200);
效果:
References:developer.mozilla.org/zh-CN/docs/…
下一章节详细解释本文用到的API。