Canvas 學習筆記 -- by Damon
canvas對于圖像的操作能力
功能:動態(tài)的圖像合成惨奕、圖形的背景、游戲界面
圖片源:
- img元素 Image()/<img>
- <video>
- <canvas>
- ImageBitmap 高性能的位圖核畴,可以低延遲地繪制
使用案例
- 繪制圖片
ctx.drawImage(image, x, y)
// image: img/canvas obj
// (x, y) start position
- 縮放 Scaling
ctx.drawImage(image, x, y, width, height)
// width, height => 控制大小
- 切片 Slicing
ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
// s => source
// d => desination
// 方法被重載了信粮,注意區(qū)別
例子: 相框
- Gecko的新屬性亮曹,控制圖像的縮放行為
cx.mozImageSmoothingEnabled = false;
用canvas替換圖片
window.onload = function() {
drawImage();
slicing();
};
// 1
function drawImage() {
var cvs = document.getElementById('my-canvas-1');
var ctx = cvs.getContext('2d');
var img = new Image();
img.src = 'img/img00003.png';
img.onload = function() {
ctx.drawImage(img, 100, 0);
var pattern = ctx.createPattern(img, 'no-repeat');
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, 300, 150);
};
}
// 2
function slicing() {
var cvs = document.getElementById('my-canvas-2');
var ctx = cvs.getContext('2d');
var frame = new Image();
frame.src = 'img/frame.jpg';
frame.onload = function() {
ctx.drawImage(frame, 0, 0);
var img = new Image();
img.src = 'img/img00004.png';
img.onload = function() {
ctx.drawImage(img, 0, 0, 200, 200, 50, 50, 200, 100);
};
};
}
// 3