drawImage共提供了三個方法:
1.在畫布上定位影像。
context.drawImage(img,x,y);
2.在畫布上定位圖像,並指定圖像的寬度和高度。
context.drawImage(img,x,y,width,height);
3.裁切影像,並在畫布上定位被裁切的部分。
context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);
參數 | #描述 |
---|---|
img | |
sx | |
sy | |
swidth | |
sheight | |
x | |
y | |
width |
height
要繪製的影像的高度。 (伸展或縮小圖像)
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>canvas绘图</title> <script> window.onload = function() { drawCanvas1(); drawCanvas2(); drawCanvas3(); } //context.drawImage(img,x,y); function drawCanvas1() { var canvas = document.getElementById("myCanvas1"); var context = canvas.getContext("2d"); //将图片绘制到canvas上 var img = new Image(); img.src = "1.jpg"; img.onload = function() { context.drawImage(img, 0, 0); }; context.textAlign = "center"; context.fillText("context.drawImage(img,x,y)画原图", 250, 350); } //context.drawImage(img,x,y,width,height); function drawCanvas2() { var canvas = document.getElementById("myCanvas2"); var context = canvas.getContext("2d"); //将图片绘制到canvas上 var img = new Image(); img.src = "1.jpg"; img.onload = function() { context.drawImage(img, 0, 0, 500, 300); }; context.textAlign = "center"; context.fillText("context.drawImage(img,x,y,width,height)指定宽和高进行拉伸和缩放", 250, 350); } //context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height); function drawCanvas3() { var canvas = document.getElementById("myCanvas3"); var context = canvas.getContext("2d"); //将图片绘制到canvas上 var img = new Image(); img.src = "1.jpg"; img.onload = function() { context.drawImage(img, 200,100, 200, 200, 0, 0, 200, 200); }; context.textAlign = "center"; context.fillText("context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height)", 250, 350); context.fillText("裁切图片的一部分绘制在画布上,并可进行缩放", 250, 370); } </script> </head> <body> <canvas id="myCanvas1" width="500" height="400" style="border:#F00 solid 1px"> 您的浏览器不支持canvas </canvas> <canvas id="myCanvas2" width="500" height="400" style="border:#F00 solid 1px"> 您的浏览器不支持canvas </canvas> <canvas id="myCanvas3" width="500" height="400" style="border:#F00 solid 1px"> 您的浏览器不支持canvas </canvas> <br /> </body> </html>
以上是HTML5 canvas畫布詳解(五)的詳細內容。更多資訊請關注PHP中文網其他相關文章!