drawImage()是一個很關鍵的方法,它可以引入圖像、畫布、視頻,並對其進行縮放或裁剪。
總共有三種表現形式:
語法 1
JavaScript Code複製內容到剪貼簿
-
context.drawImage(img,dx,dy);
文法 2
JavaScript Code複製內容到剪貼簿
-
context.drawImage(img,dx,dy,dw,dw);
文法 3
JavaScript Code複製內容到剪貼簿
-
context.drawImage(img,sx,sy,sw,sh,dx,dy,dw,dh);
來看看座標草圖:
PS: 不要在樣式中定義
下面,我們載入一個圖片試試。
JavaScript Code複製內容到剪貼簿
-
html>
- "zh">
-
-
"UTF-8">
-
drawImage()
-
-
body { background: url("./images/bg3.jpg") /images/bg3.jpg") eat>;
- #canvas { border: 1px solid #aaaaaa; display: block; margin: 50px auto; }
-
-
-
"canvas-warp">
-
-
-
<script> <li> <span>
window.onload = <li class="alt"><span>function<span class="keyword">(){ <span>
<li><span>var<span class="keyword"> canvas = document.getElementById(<span>"><
<span class="string"> canvas.width = 800; <span>
canvas.height = 600; <li class="alt"> <span>
<li><span>var context = canvas.getContext(<li class="alt"><span>"21>"29><);
<span class="keyword"> context.fillStyle = <span>"#FFF"<span class="string">; <span>; <li> <span>
<span class="string"> context.fillRect(0,0,800,600); <span>
<li class="alt"> <span>
<li><span>var img = <li class="alt"><🎜
<span> img.src = <span class="keyword">"./images/20-1.jpg"<span>; <span class="keyword"> ; <span> ;
<li> img.onload = <span>function<span class="string">(){ <span> (){ <li class="alt"> <span>(){ <span class="keyword"> <span>(){ <li>(){ <span> (){ <li class="alt"> <span>(){ <li>
<span> context.drawImage(img,200,50); <li class="alt">
<span> } <li>
<span> }; <li class="alt">
<span></script>
運行結果:
建立相框:
這裡,我們結合clip()和drawImage()以及三次貝塞爾曲線bezierCurveTo(),來為上面一個案例,加上一個心形的相框~
JavaScript Code複製內容到剪貼簿
-
-
"zh">
-
-
"UTF-8">
-
绘制心形相框
-
-
-
-
"canvas-warp">
-
-
你的浏览器居然不支持Canvas?!赶快换一个吧!!
-
-
-
-
-
window.onload = 函數(){
-
var canvas = document.getElementById("
canvas.width = 800; -
canvas.height = 600; -
-
var context = canvas.getContext("2d"
context.fillStyle =
- "#FFF";
context.fillRect(0,0,800,600);
-
-
context.beginPath();
-
context.moveTo(400,260);
-
context.bezierCurveTo(450,220,450,300,400,315);
-
context.bezierCurveTo(350,300,350,220,400,260);
-
context.clip();
-
context.closePath();
-
-
- var img = new
img.src =
- "./images/20-1.jpg";
img.onload =
- 函數(){ (){
-
context.drawImage(img,348,240,100,100);
-
}
-
};
-
腳本>