Fork Me On Github

基本

获取页面元素

let canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d");

虚拟缓存(不显示在页面,主要是用于缓存部分场景)

let cacheCanvas = document.createElement("canvas"),
    cacheContext = cacheCanvas.getContext("2d");

应用缓存

context.drawImage(cacheCanvas, 0, 0); 

绘制基本图形

绘制文字

context.font = 'bold 35px Arial';
context.textAlign = 'center';
context.textBaseline = 'bottom';
context.fillStyle = '#ccc';
context.strokeText("Hello Canvas", 150, 100, 200);
context.fillText("Hello Canvas", 180, 140);

绘制图片

let img = new Image();
img.src = '';
if(img.complete) {
    context.drawImage(img, 0, 0); 
} else {
    img.onload = function(){
     context.drawImage(img, 0, 0); 
   };
   img.onerror = function(){
     alert('加载失败,请重试');
   };
}

高级绘图

绘制游戏画面,先把背景、元素都分成不同的缓存,设定刷新时间,并组成不同的场景

点击查看全文
0 197 0