Skip to content
此页目录
本文总阅读量

Canvas 绘制图形、图像

绘制图形

矩形

js
ctx.beginPath()
// x,y, w,h
ctx.rect(10,10,300,100)
ctx.fillStyle="orange"
ctx.fill()

ctx.beginPath()
ctx.fillStyle="green"

// 绘制并填充
ctx.fillRect(50,50,200,200)
ctx.beginPath()
ctx.strokeRect(50,50,30,89)

// 清除区域
ctx.clearRect(0,0,600,200)

绘制圆、圆弧和扇形

js
ctx.beginPath()
ctx.arc(300,200,150,0,0.5*Math.PI,false)
ctx.stroke()
ctx.beginPath()
ctx.arc(300,200,150,0,2*Math.PI,false)
ctx.stroke()

绘制文本

js
ctx.font="50px 宋体"
ctx.textAlign="start"
ctx.textBaseline="top"
ctx.fillText("hello",100,100)

绘制图像

drawImage() 方法在画布上绘制图像;

三个参数:

js
context.drawImage(img,x,y);

五个参数:

js
context.drawImage(img,x,y,width,height);

九个参数:

js
context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);

let img=new Image()
img.src="index.jpg"
img.onload=function(){
  // 将图片放到哪个位置
  // ctx.drawImage(img,100,100)

  // 将图片放到哪个位置并设置宽高
  // ctx.drawImage(img,10,10,400,400)

  // 将图片裁剪后放到哪个位置并设置宽高
  ctx.drawImage(img,180,220,71,25,0,0,200,150)

}

评论

交流群