canvas

1 图形编程canvas

1.1 基本用法

<canvas id="tutorial" width="300" height="150"></canvas>

1.2 渲染上下文

var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');

1.3 globalCompositeOperatioin

ctx.globalCompositeOperation = 'destination-over';

globalCompositeOperation

1.4 基本的绘图步骤

基本的绘图步骤

1.5 完整教程

Mozilla官方教程

1.6 应用实例

/* 太阳、地球、月亮 */
var sun = new Image();
var moon = new Image();
var earth = new Image();
function init(){
    sun.src = 'Canvas_sum.png';
    moon.src = 'Canvas_moon.png';
    earth.src = 'Canvas_earth.png';
    window.requestAnimationFrame(draw);
}
function draw(){

    var ctx = document.getElementById('canvas').getContext('2d');
    
    ctx.globalCompositeOperation = 'destination-over';
    ctx.clearRect(0,0,390,300);//clear canvas
    
    ctx.fillStyle = 'rgba(0,0,0,0.4)';
    ctx.strokeStyle = 'rgba(0,153,225,0.4)';
    ctx.save();
    ctx.translate(150,150);
    
    //earth
    var time = new Date();
    ctx.rotate(((2*Math.PI)/60)*time.getSeconds() +((2*Math.PI)/60000)*time.getMilliseconds());
    ctx.translate(105,0);
    ctx.fillRect(0,12,50,24);//shadow
    ctx.drawImage(earth,-12,-12);
    
    //moon
    ctx.rotate(((2*Math.PI)/6)*time.getSeconds() + ((2*Math.PI)/6000)*time.getMilliseconds());
    ctx.translate(0,28.5);
    ctx.drawImage(moon,-3.5,-3.5);
    
    ctx.restore();
    
    ctx.beginPath();
    ctx.arc(150,150,105,0,Math.PI*2,false);//earth arbit
    ctx.stroke();
    
    ctx.drawImage(sun,0,0,300,300);
    
    window.requestAnimationFrame(draw);
    
}
init();
原文地址:https://www.cnblogs.com/luwanlin/p/14306258.html