本文通过代码小例子带你走进 Canvas
1、绘制线条
<canvas id="canvas" width="800" height="600"></canvas>
<script>
const canvas = document.querySelector('#canvas')
const ctx = canvas.getContext('2d');
ctx.lineWidth = 3
ctx.fillStyle = 'pink'
ctx.strokeStyle = 'red'
ctx.moveTo(100,100)
ctx.lineTo(200,200)
ctx.lineTo(200,300)
ctx.lineTo(100,100)
ctx.stroke()
ctx.fill()
ctx.beginPath()
ctx.moveTo(300,300)
ctx.lineTo(300,400)
ctx.lineTo(400,400)
ctx.closePath()
ctx.stroke()
ctx.fill()
</script>
2、绘制图形
<script>
ctx.rect(100,150,200,200)
ctx.stroke()
ctx.fill()
ctx.strokeRect(100, 100, 50, 50);
ctx.fillRect(150, 50, 50, 50);
ctx.clearRect(165, 60, 20, 20);
ctx.arc(300, 300, 100, 0, Math.PI * 2);
ctx.stroke();
ctx.fill();
</script>
3、渐变色及文字
<script>
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
const gra = ctx.createLinearGradient(20, 20, 100, 100);
gra.addColorStop(0, "skyblue");
gra.addColorStop(0.5, "pink");
gra.addColorStop(0, "cyan");
ctx.fillStyle = gra;
ctx.fillRect(20, 20, 100, 100);
ctx.font = '50px "微软雅黑"';
ctx.shadowColor = "black";
ctx.shadowBlur = 6;
ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;
ctx.fillText("你好!", 300, 300);
ctx.strokeText("你好!", 400, 400);
</script>
4、画板案例
<canvas id="canvas" width="800" height="600"></canvas>
<script>
const canvas = document.querySelector('#canvas')
const ctx = canvas.getContext('2d');
ctx.lineWidth = 3
ctx.strokeStyle = 'red'
let flag = false
canvas.onmousedown = function(){
flag = true
ctx.beginPath();
}
canvas.onmousemove = function(e){
if(!flag) return
ctx.lineTo(e.clientX,e.clientY)
ctx.stroke()
}
canvas.onmouseup = function(){
flag = false
}
</script>