Canvas--繪製圖像及視頻

一、經過 drawImage() 方法在canvas上繪製圖像
canvas

  drawImage() 有三種用法:ide

  1) context.drawImage(img,x,y) : 在畫布上定位圖像,圖像以自身大小顯示。spa

  2) context.drawImage(img,x,y,width,height) : 在畫布上定位圖像,並規定圖像的寬度和高度。code

  3) context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height) : 剪切圖像,並在畫布上定位被剪切的部分。視頻

  參數:
blog

    img  ---- 規定要使用的圖像、畫布或視頻。get

      x    ---- 在畫布上放置圖像的 x 座標位置。io

      y    ---- 在畫布上放置圖像的 y 座標位置。function

     width ---- 可選。要使用的圖像的寬度(伸展或縮小圖像)。class

     height---- 可選。要使用的圖像的高度(伸展或縮小圖像)。

      sx   ---- 可選。開始剪切的 x 座標位置。

      sy   ---- 可選。開始剪切的 y 座標位置。

  swidth ---- 可選。被剪切圖像的寬度。

  sheight---- 可選。被剪切圖像的高度。

1 var IMG = new Image()
2 IMG.src = 'img.jpg'
3 
4 IMG.onload = function() {
5     context.drawImage(IMG, 0, 0)
6     context.drawImage(IMG, 740, 0, 736, 490)
7     context.drawImage(IMG, 0, 0, 300, 200, 0, 500, 300, 200)
8 }

二、繪製視頻

<video id="video" controls width="270">
    <source src="video/mov_bbb.mp4" type="video/mp4">
    <source src="video/mov_bbb.ogg" type="video/ogg">
</video>
<canvas id="canvas">Your browser does not support canvas</canvas>
 1 var video = document.getElementById('video')
 2 var timer
 3 
 4 if (window.requestAnimationFrame) {
 5     video.addEventListener('play', draw)
 6 } else {
 7     video.addEventListener('play', function() {
 8         timer = setInterval(function() {
 9             context.drawImage(video, 0, 0)
10         }, 20)
11     })
12 
13     video.addEventListener('pause',function(){
14         clearInterval(timer)
15     })
16 
17     video.addEventListener('pause',function(){
18         clearInterval(timer)
19     })
20 
21 }
22 
23 function draw() {
24     var stop = window.requestAnimationFrame(draw)
25     context.drawImage(video, 0, 0)
26 
27     video.addEventListener('pause', function() {
28         window.cancelAnimationFrame(stop)
29     })
30 
31     video.addEventListener('ended', function() {
32         window.cancelAnimationFrame(stop)
33     })
34 }

相關文章
相關標籤/搜索