canvas动画思想
export class AppComponent implements OnInit{
canvas
ctx
left=100
ngOnInit(): void {
this.canvas = document.getElementById("canvas")
this.ctx = this.canvas.getContext("2d")
this.ctx.fillStyle = "blue"
//this.ctx.fillRect(100,100,100,100)
setInterval(()=>{
this.ctx.clearRect(0,0,300,300)
this.left++
this.ctx.fillRect(this.left,100,100,100)
},100)
console.log(this.ctx)
}
}
canvas 面向对象思想
export class AppComponent implements OnInit{
canvas
ctx
ngOnInit(): void {
//获取画布
this.canvas = document.getElementById("canvas")
//获取上下文
this.ctx = this.canvas.getContext("2d")
//维护方法
function Rect(x,y,w,h,color){
this.x= x;
this.y= y;
this.w = w;
this.h=h;
this.color =color;
}
//更新方法,x坐标加1(改变图形位置)
Rect.prototype.update = function(){
this.x++;
}
//渲染方法
Rect.prototype.render = function(){
this.bind.ctx.fillStyle = "blue"
this.bind.ctx.fillRect(100,100,50,50,);
}
var r1 = new Rect(100,100,50,50,"blue")
setInterval(()=>{
this.ctx.clearRect(0,0,this.canvas.whdth,this.canvas.height)
r1.update()
r1.render()
// console.log("hello")
},1000)
console.log(this.ctx)
}
}
绘制矩形、直线
- 填充矩形
export class AppComponent implements OnInit{
canvas
ctx
ngOnInit(): void {
//获取画布
this.canvas = document.getElementById("canvas")
//获取上下文
this.ctx = this.canvas.getContext("2d")
//填充颜色
this.ctx.fillStyle = "blue"
//开始绘制填充矩形
this.ctx.fillRect(100,100,100,100)
console.log(this.ctx)
}
}
- 矩形边框
export class AppComponent implements OnInit{
canvas
ctx
ngOnInit(): void {
//获取画布
this.canvas = document.getElementById("canvas")
//获取上下文
this.ctx = this.canvas.getContext("2d")
//边框颜色
this.ctx.strokeStyle="red"
//开始绘制
this.ctx.strokeRect(100,100,100,100)
console.log(this.ctx)
}
}
擦除画布
this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)
- 绘制路径
(逆时针绘制)
export class AppComponent implements OnInit{
canvas
ctx
ngOnInit(): void {
//获取画布
this.canvas = document.getElementById("canvas")
//获取上下文
this.ctx = this.canvas.getContext("2d")
//创建一个路径
this.ctx.beginPath()
//移动画笔绘制点
this.ctx.moveTo(100,100)
//描述行进路径节点
this.ctx.lineTo(200,200)
this.ctx.lineTo(400,180)
this.ctx.lineTo(380,50)
//封闭路径
this.ctx.closePath()
//画笔颜色
this.ctx.strokeStyle = 'red'
//开始绘制
this.ctx.stroke()
}
}
线条可以不封闭---this.ctx.closePath(),但fill会自动封闭
image.png
绘制圆弧
export class AppComponent implements OnInit{
canvas
ctx
ngOnInit(): void {
//获取画布
this.canvas = document.getElementById("canvas")
//获取上下文
this.ctx = this.canvas.getContext("2d")
this.ctx.arc(200,200,100,0,2*Math.PI,false)
//this.ctx.arc(200,200,100,0,2*3.14,false)
this.ctx.fill() //填充
// this.ctx.stroke() //边框
}
}
鼠标炫彩小球效果
小球触边反弹
小球靠近连线
线型
渲染图片到画布
Document
资源管理器的封装
变形
刮刮乐
Document
中奖100万
拖拽
Document