Canvas 绘图回顾

Fork Me On Github

基本

获取页面元素

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

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

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

应用缓存

js
 
context.drawImage(cacheCanvas, 0, 0); 
1

绘制基本图形

绘制文字

js
      
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);
123456

绘制图片

js
            
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('加载失败,请重试');
   };
}
123456789101112

高级绘图

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

点击查看全文
0 418 0