canvas图像

244 阅读1分钟

前言

课件地址

github.com/buglas/canv…

课堂目标

1.理解图像的获取方式。

2.在canvas 中灵活绘制图像

知识点

  1. 图像源
  2. 绘制图像的方法 drawImage()

1-图像源

这里说的图像源就是canvas 在绘制图像时所用的源文件。

常见的图像源有三种:

  • 图像元素 img
  • 视频元素 video
  • canvas 画布

2-在canvas 中绘制图像

drawImage() 方法可以将一张图像绘制到canvas 画布里。

drawImage() 方法因参数数量不同,其具体功能也不同:

  • 绘图 + 位移:drawImage(image, x, y)

image-20220424173347270

代码示例:

const ctx=canvas.getContext('2d');

const img=new Image();
img.src='./images/dog.jpg';
img.onload=function(){
  /*图像尺寸*/
  const {width,height}=img;

  /*绘图+移动 drawImage(image, x, y) */
  ctx.drawImage(
    img,
    50,100
  );

};
  • 绘图 + 位移 + 缩放:drawImage(image, x, y,width,height)

image-20220424172206218

代码示例:

const ctx=canvas.getContext('2d');

const img=new Image();
img.src='./images/dog.jpg';
img.onload=function(){
  /*图像尺寸*/
  const {width,height}=img;

  /*绘图+移动+缩放 drawImage(image, x, y,width,height) */
  ctx.drawImage(
    img,
    0,0,
    width*2,height*2
  )

};
  • 绘图 + 裁切 + 位移 + 缩放:drawImage(image, x1, y1,w1,h1,x2,y2,w2,h2)

image-20220424173259490

此时的drawImage() 方法已经具备了相机视口的功能。

代码示例:

const ctx=canvas.getContext('2d');

const img=new Image();
img.src='./images/dog.jpg';
img.onload=function(){
  /*图像尺寸*/
  const {width,height}=img;

  /*绘图+裁剪+移动+缩放 drawImage(image, x1, y1,w1,h1,x2,y2,w2,h2) */
  ctx.drawImage(
    img,
    //裁剪
    width/2,height/2,
    width/2,height/2,
    //位移+缩放
    100,100,
    width,height
  )

};

案例-在canvas 中播放视频

之前我们说过,video 也可以做图像源,接下来,我们就在canvas 里播放一个video 视频:

ripples

代码实现:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>视频</title>
    <style>
        #canvas{background: antiquewhite}
    </style>
</head>
<body>
<video id="vid" controls autoplay loop muted>
    <source src="./images/ripples.mp4" type='video/mp4'>
</video>
<div>
    <canvas id="canvas" width="400" height="282"></canvas>
</div>
<script>
    //获取图像源
    const vid=document.getElementById('vid');
    //获取canvas
    const canvas=document.getElementById('canvas');
    //获取上下文对象
    const ctx=canvas.getContext('2d');


    /*视频事件:
    *   play 视频播放
    *   pause 暂停
    * */
    let interval=null;
    vid.addEventListener('play',function(){
        interval=setInterval(function(){
            ctx.drawImage(vid,0,0);
        },40)
    })

    vid.addEventListener('pause',function(){
        clearInterval(interval);
    })
</script>
</body>
</html>