Html5开发-使用Canvas绘制图片
生活随笔
收集整理的這篇文章主要介紹了
Html5开发-使用Canvas绘制图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
呈現圖片 | drawImage()
canvas/media/image.html
<html>
<head>
<title>在 canvas 上呈現圖片的 demo</title>
</head>
<body>
<canvas id="canvas" width="800" height="600" style="background-color: rgb(222, 222, 222)">
您的瀏覽器不支持 canvas 標簽
</canvas>
<br />
<button type="button" onclick="drawIt();">在畫布上呈現圖片</button>
<button type="button" onclick="clearIt();">清除畫布</button>
<script type="text/javascript">
var ctx = document.getElementById('canvas').getContext('2d');
function drawIt() {
clearIt();
var img = new Image();
img.onload = function () {
/*
* context.drawImage() 的可繪制對象包括:HTMLImageElement, HTMLVideoElement, HTMLCanvasElement
*
* context.drawImage(image, x, y) - 繪制圖像
* image - 圖像對象,可以來自 img 標簽
* x - 圖像繪制到畫布后的左上角的 x 坐標
* y - 圖像繪制到畫布后的左上角的 y 坐標
*
* context.drawImage(image, x, y, width, height) - 繪制圖像
* image - 圖像對象,可以來自 img 標簽
* x - 圖像繪制到畫布后的左上角的 x 坐標
* y - 圖像繪制到畫布后的左上角的 y 坐標
* width - 圖像繪制到畫布后的寬
* height - 圖像繪制到畫布后的高
*
* context.drawImage(image, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight) - 繪制圖像
* image - 圖像對象,可以來自 img 標簽
* sourceX - 截取源圖像,相對于源圖像的左上角的 x 坐標,
* sourceY - 截取源圖像,相對于源圖像的左上角的 y 坐標,
* sourceWidth - 截取源圖像,需要截取的寬
* sourceHeight - 截取源圖像,需要截取的高
* destX - 圖像繪制到畫布后的左上角的 x 坐標
* destY - 圖像繪制到畫布后的左上角的 y 坐標
* destWidth - 圖像繪制到畫布后的寬
* destHeight - 圖像繪制到畫布后的高
*
*/
ctx.drawImage(img, 0, 0); // 按圖像原始大小顯示到畫布上
ctx.drawImage(img, 0, 0, 200, 200); // 顯示圖像到畫布上,并指定其寬高
ctx.drawImage(img, 50, 0, 400, 100, 0, 300, 200, 50); // 截取源圖像的一部分顯示到畫布上,并指定被截取部分顯示時的寬和高
}
img.src = "http://www.w3.org/html/logo/downloads/HTML5_Logo_512.png";
// img.src = "http://www.cnblogs.com/assets/html5_logo.png";
}
function clearIt() {
ctx.clearRect(0, 0, 800, 600);
}
</script>
</body>
</html>
總結
以上是生活随笔為你收集整理的Html5开发-使用Canvas绘制图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Html5画布(canvas)实例之绘制
- 下一篇: Html5中新增的表单元素详解