03. 绘制图片

2022-12-30 11:34:14发布
31

canvas中使用drawImage方法来绘制图片,该方法有3中模式 :

模式1 :drawImage(image, x, y)
模式2 :drawImage(image, x, y, w, h) 
模式3 :drawImage(image, sx, sy, sw, sh, x, y, w, h)


模式1

const paint = document.querySelector('canvas').getContext('2d');
const img = document.createElement('img');
img.src = './mario.png';
img.onload = function() { //此处一定要加onload事件,图片要加载完了之后才能绘制出来
    paint.drawImage(img, 0, 0);
}


模式2

模式2可以指定图片的宽高

const paint = document.querySelector('canvas').getContext('2d');
const img = document.createElement('img');
img.src = './mario.png';
img.onload = function () {
    paint.drawImage(img, 0, 0, 300, 300);
}


模式3

模式3可以指定绘制图片的区域,如我只想绘制马里奥的头部, 如下图 :

const paint = document.querySelector('canvas').getContext('2d');
const img = document.createElement('img');
img.src = './mario.png';
img.onload = function () {
    paint.drawImage(this, 60, 0, 150, 130, 0 , 0, 100, 100);
}

利用模式3这种特性,我们可以在一张很多帧的图片上绘制出一组动画。 如下图 :

图片长1200, 高为120

const paint = document.querySelector('canvas').getContext('2d');
const img = document.createElement('img');
img.src = './fish.png';
const imgW = 120;
const imgH = 120;
let step = 0;

function logic() {
    paint.clearRect(0, 0, 500, 500); // 刷屏
    paint.drawImage(img, step, 0, imgW, imgH, 0, 0, imgW, imgH);
    step += imgW;
    if (step >= imgW * 10) {
        step = 0;
    }
    window.requestAnimationFrame(logic);
}

window.requestAnimationFrame(logic);