ctx.lineWidth=20;
// ctx.lineJoin = 'round';
ctx.lineJoin = 'bevel';//拐点
ctx.lineCap ='round'//两端
ctx.moveTo(100,100);
ctx.lineTo(150,50);
ctx.lineTo(200,100);
ctx.stroke();
let canvas = document.querySelector('canvas')
let ctx = canvas.getContext('2d');
ctx.setLineDash([4,1])//必须为数组
ctx.lineDashOffset = 4//虚线偏移
ctx.moveTo(100,100.5);
ctx.lineTo(200,100.5);//如果是100而不是100.5,那线条就是2px,且模糊
ctx.stroke();
console.log(ctx.getLineDash())//获取虚线的lineDash
ctx.rect(100,100,200,100);//(x,y,宽,高)
ctx.stroke();
//ctx.strokeRect(100,100,200,100);//(x,y,宽,高)
//ctx.fillRect(100,100,200,100);
//ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);//擦掉
<template>
<div class="contain">
<canvas width="600" height="400"></canvas>
</div>
</template>
<script>
export default {
mounted(){
let canvas = document.querySelector('canvas')
let ctx = canvas.getContext('2d');
var lineGradient = ctx.createLinearGradient(100,100,500,100);//渐变的起始点和终点
lineGradient.addColorStop(0,'pink');
lineGradient.addColorStop(0.5,'yellow');
lineGradient.addColorStop(1,'blue');
ctx.fillStyle=lineGradient
ctx.fillRect(100,100,400,100);//被渐变填充的形状
}
};
</script>
<style lang="scss">
canvas{
border:1px solid #ccc;
}
</style>
for(let i=1;i<600;i++){
ctx.lineTo(i,10*Math.sin(i*100)+200)
}
ctx.stroke()
let w = ctx.canvas.width
let h = ctx.canvas.height
ctx.arc(w/2,h/2,150,Math.PI/2,Math.PI,true)//arc(x0,y0,半径,起始弧度,结束弧度,true为逆时针)
ctx.stroke()
let w = ctx.canvas.width
let h = ctx.canvas.height
ctx.moveTo(w/2,h/2)
ctx.arc(w/2,h/2,50,Math.PI/2,Math.PI,true)
ctx.closePath()
ctx.fill()
<template>
<div class="contain">
<canvas width="600" height="400"></canvas>
</div>
</template>
<script>
export default {
methods:{
getRandomColor(){
let r = Math.floor(Math.random()*256)//random从0到1,不包括1
let g = Math.floor(Math.random()*256)
let b = Math.floor(Math.random()*256)
return 'rgb('+r+','+g+','+b+')'
}
},
mounted(){
let canvas = document.querySelector('canvas')
let ctx = canvas.getContext('2d');
let w = ctx.canvas.width
let h = ctx.canvas.height
for(let i = 0;i<6;i++){
ctx.beginPath();
ctx.moveTo(w/2,h/2)
ctx.arc(w/2,h/2,50,i*(Math.PI*2/6),(i+1)*(Math.PI*2/6))
ctx.fillStyle = this.getRandomColor();
ctx.fill()
}
}
};
</script>
<style lang="scss">
canvas{
border:1px solid #ccc;
}
</style>
let canvas = document.querySelector('canvas')
let ctx = canvas.getContext('2d');
let w = ctx.canvas.width
let h = ctx.canvas.height
ctx.moveTo(w/2-0.5,0);
ctx.lineTo(w/2-0.5,h);
ctx.moveTo(0,h/2-0.5);
ctx.lineTo(w,h/2-0.5);
ctx.stroke();
ctx.beginPath();
let x0 = w/2;
let y0= h/2;
ctx.font="40px Microsoft YaHei";
ctx.textBaseline = 'middle'
ctx.textAlign ='center'//基于x0,y0
let text = '按时休息'
ctx.strokeText(text,x0,y0);
ctx.fillText(text,x0,y0);
let textWidth=ctx.measureText(text).width
ctx.moveTo(x0-textWidth/2,y0+20-0.5)
ctx.lineTo(x0+textWidth/2,y0+20-0.5)
ctx.stroke()
进阶实战:
非零环绕原则:https://blog.csdn.net/weixin_41254345/article/details/104892843
用canvas画平行线:https://blog.csdn.net/weixin_41254345/article/details/104893140