# 大綱 ## 參考 [w3](https://www.w3schools.com/tags/canvas_createlineargradient.asp) [rain](https://github.com/imgss/gif_rain_code/blob/master/gif/index.html) [canvas 中](https://developer.mozilla.org/zh-TW/docs/Web/API/Canvas_API/Tutorial/Using_images) [blog](https://stackoverflow.com/questions/34447517/how-to-optimize-animated-gif-by-using-client-side-javascript) [ImgData](https://juejin.im/post/5ba06596f265da0acc7957e4) # 註解 ## 分解說明 ## 函數 ### canvas 函數說明 **createLinearGradient(x0,y0,x1,y1)** 指定畫布上的開始位置, Parameter Description x0 The x-coordinate of the start point of the gradient y0 The y-coordinate of the start point of the gradient x1 The x-coordinate of the end point of the gradient y1 The y-coordinate of the end point of the gradient **fillRect(x,y,width,height)** |參數|說明| |---|---| |x |左上| |y |右下| |width| 寬, in pixels| |height| 高, in pixels| **drawImage()** - drawImage(image, x, y) 原圖顯示,(x,y) 表示canvas 的開始位置。 - drawImage(image, x, y, width, height) (x,y)同上,原圖按照指定的width(寬)、height(高)縮放影像. - drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) 來源影像(s)中,位置(sx, sy)開始,寬高(sWidth,sHeight)切割;然後放置到畫布開始位置(dx, dy),且按照(dWidth,dHeight)縮放。 ``` html {height="200px"}

Note: The canvas tag is not supported in Internet Explorer 8 and earlier versions.

``` 行27:可以知道 建立完成的linearGradient 只是用來填充用的。這裡填充矩形物件。 # dynamic gif ## 主程式 分別用了兩種程式庫 一個是`jsgif` @import "gifTest1.html" {code_block=true class="line-numbers" } 一個是`gif.js` @import "gifTest2.html" {code_block=true class="line-numbers" } ## 分部測試 [gifTest1_a.html](gifTest1_a.html) 只是用來測試image,canvasj 之間的關係。例如,如果沒有利用onload事件,則可能無法在`canvas`標籤上畫出圖形。 @import "gifTest1_a.html" {code_block=true class="line-numbers" } 上面只有一個圖形,這裡多個。 [gifTest1_b.html](gifTest1_b.html) @import "gifTest1_b.html" {code_block=true class="line-numbers" } 和上面的分別是,不用createElement("img") ,直接使用 `new Image();`。 順便看看怎樣把1個圖形轉成gif。 [gifTest1_c.html](gifTest1_c.html) @import "gifTest1_c.html" {code_block=true class="line-numbers" } ### onload event Using newer JavaScript features: ``` js function loadImage(url) { return new Promise(resolve => { let i = new Image(); i.onload = ()=>{resolve(i)}; i.src=url; }); } let img = await loadImage("0001.jpg"); ctx.drawImage(img, 0, 0); ```