大綱
參考
註解
分解說明
函數
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>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var grd = ctx.createLinearGradient(0, 0, 170, 0);
grd.addColorStop(0, "black");
grd.addColorStop(1, "white");
ctx.fillStyle = grd; //grd
ctx.fillRect(20, 20, 150, 100);//注意:這裡20+15=170,在createLinearGradient()中的x0=170
</script>
<p><strong>Note:</strong> The canvas tag is not supported in Internet
Explorer 8 and earlier versions.</p>
</body>
</html>
行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 只是用來測試image,canvasj 之間的關係。例如,如果沒有利用onload事件,則可能無法在canvas
標籤上畫出圖形。
@import "gifTest1_a.html" {code_block=true class="line-numbers" }
上面只有一個圖形,這裡多個。 gifTest1_b.html @import "gifTest1_b.html" {code_block=true class="line-numbers" }
和上面的分別是,不用createElement("img") ,直接使用 new Image();
。 順便看看怎樣把1個圖形轉成gif。
gifTest1_c.html
@import "gifTest1_c.html" {code_block=true class="line-numbers" }
onload event
Using newer JavaScript features:
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);