這次給大家帶來用H5的canvas做恐怖動畫,用H5的canvas做恐怖動畫的注意事項有哪些,下面就是實戰案例,一起來看一下。
canvas可以實作一些有趣的效果,動畫實作。以一個簡單的頁面實作了解一下基礎的畫圖方法。
效果
萬聖節快樂
預備知識let canvas = document.getElementById('canvas');let context = canvas.getContext('2d');
開始路徑context.beginPath();
beginPath()方法在畫布上開始一條繪制路徑,或重置目前的路徑。
移動路徑context.moveTo();
moveTo()方法把路徑移動到畫布中指定點,不建立線條。
添加線條context.lineTo();
lineTo()方法添加一個新點,在畫布中建立該點到指定點的線條。
畫圖drawImagecontext.drawImage(image,x,y);
drawImage()方法可以在畫布上繪制圖像、畫布或視訊,也可以繪制圖像的某些部分,增加/減少圖像的尺寸。
擷取像素資料context.getImageData(x,y,width,height);
getImageData()方法可以擷取畫布imageData對象,該對象指定了矩形的像素資料。
在imageData對象中每個像素都存在rgba值,以數組形式存儲在data屬性中。
放回像素資料context.putImageData(imageData,x,y);
putImageData()方法将擷取的圖像資料放回到畫布上。
實作
htmlClick
csshtml,body,canvas { width: 100%; height: 100%; margin: 0;
}.switch { position: absolute; top: 70%; right: 10%; width: 50px; height: 50px; border-radius: 50px; outline: none; cursor: pointer; animation: switch-animate alternate infinite ease 1s 0s;
}
@keyframes switch-animate { from { box-shadow: 0 0 30px #ece9c5;
} to { box-shadow: 0 0 100px #eae5a7;
}
}
js(function () { class Halloween { constructor(id) { this.canvas = document.getElementById(id); this.ctx = this.canvas.getContext('2d'); this.w = this.canvas.width; this.h = this.canvas.height; this.data = [];
} //初始畫布
initDraw(img) { this.w = this.canvas.width = img.width; this.h = this.canvas.height = img.height; this.ctx.drawImage(img, 0, 0); this.data = this.ctx.getImageData(0, 0, this.w, this.h);
} //顯示文字
drawText() { this.ctx.font = '60px Verdana'; this.ctx.fillStyle = '#ffffff'; this.ctx.fillText('萬聖節快樂', 350, 280);
} //閃電
lightning() { let ctx = this.ctx;
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(800, 10);
ctx.lineTo(600, 100);
ctx.lineTo(500, 200);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(600, 100);
ctx.lineTo(650, 170);
ctx.stroke()
} //打雷
thunder() { let timer = Math.floor(800 * Math.random()); this.reverse(); this.lightning(); this.drawText();
setTimeout(() => { this.reset();
}, timer);
} //反轉畫布
reverse() { let imgData = this.ctx.getImageData(0, 0, this.w, this.h); for (var i = 0, len = imgData.data.length; i < len; i += 4) {
imgData.data[i] = 255 - imgData.data[i];
imgData.data[i + 1] = 255 - imgData.data[i + 1];
imgData.data[i + 2] = 255 - imgData.data[i + 2];
imgData.data[i + 3] = 255;
} this.ctx.putImageData(imgData, 0, 0);
} //重置畫布
reset() { this.ctx.putImageData(this.data, 0, 0);
}
} let halloween = new Halloween('canvas'); let canvas = document.getElementById('canvas'); let ctx = canvas.getContext('2d'); let img = new Image();
img.src = '/images/halloween.png';
img.onload = () => {
halloween.initDraw(img);
} document.getElementById('click').onclick = () => {
halloween.thunder();
}
})();
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
推薦閱讀: