1.基本格式
<canvas id="myCanvas" width="300" height="300"></canvas>
2.获取元素,添加画笔2d
let c = document.getElementById("myCanvas");
let ctx = c.getContext("2d");
4.画线基本格式
ctx.moveTo(100, 100);//开始起点
ctx.lineTo(200,100);//分别为x轴,和y轴
ctx.lineTo(200,100);//分别为x轴,和y轴
ctx.stroke();//结束画画
5.渐变色
var grd = ctx.createLinearGradient(20, 20, 200, 0);
grd.addColorStop(0, "red");
grd.addColorStop(1, "blue");
ctx.fillStyle = grd;
正方形
ctx.fillRect(200, 10, 200, 100);
ctx.stroke();
长方形
ctx.fillRect(200, 10, 200, 100);
ctx.stroke();
3圆形
var grd = ctx.createRadialGradient(75, 50, 5, 90, 60, 100);
grd.addColorStop(0, "red");
grd.addColorStop(1, "blue");
ctx.beginPath();
ctx.arc(500, 50, 40, 0, 2 * Math.PI);
ctx.fillStyle = grd;
ctx.fill();
ctx.stroke();
var grd = ctx.createRadialGradient(75, 50, 5, 90, 60, 100);
grd.addColorStop(0, "red");
grd.addColorStop(1, "blue");
ctx.beginPath();
ctx.moveTo(600, 90);
ctx.arc(600, 50, 40, 0, Math.PI, true);
ctx.fillStyle = grd;
ctx.fill();
ctx.stroke;
4.文字美化
var gradient = ctx.createLinearGradient(0, 0, c.width, 0);
gradient.addColorStop("0", "white");
gradient.addColorStop("0.5", "red");
gradient.addColorStop("1.0", "blue");
// Fill with gradient
ctx.fillStyle = gradient;
ctx.font = "30px Arial";
ctx.fillText("李鹏浩", 650, 90);
ctx.stroke;
5.折线图
var c1 = document.getElementById("mycanvas");
var ctx1 = c1.getContext("2d");
var grd = ctx1.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "red");
grd.addColorStop(1, "pink");
ctx1.fillStyle = grd;
let n = 0;
let num = 350;
let a = 50;
for (let i = 1; i <= 15; i++) {
ctx1.fillRect(n, a, 50, num);
ctx1.stroke();
num = num - 20;
a = a + 20;
n = n + 100;
}
ctx1.stroke();
var c3 = document.getElementById("mycanvas3");
var ctx3 = c3.getContext("2d");
ctx3.moveTo(30, 30);
ctx3.lineTo(30, 380);
ctx3.lineTo(1000, 380);
let num1 = 40;
let num2 = 40;
for (let i = 0; i < 10; i++) {
ctx3.moveTo(30, num2);
ctx3.lineTo(40, num2);
num2 = num2 + 35;
}
let num3 = 60;
for (let i = 0; i < 26; i++) {
ctx3.moveTo(num3, 380);
ctx3.lineTo(num3, 370);
num3 = num3 + 35;
}
function ranDom(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
ranDom(100, 1000);
let num4 = 100;
ctx3.moveTo(60, ranDom(10, 100));
for (let i = 0; i < 15; i++) {
ctx3.lineTo(num4, ranDom(10, 350));
num4 = num4 + +ranDom(10, 100);
}
ctx3.stroke();
v