Place object between another two

让人想犯罪 __ 提交于 2019-12-02 08:47:55

You just need to change a little on the orders of things in the code - composite modes are really not needed in this case:

  • All static elements like the sun and the earth orbit, can be rendered once and set as for example background to the element.
  • Draw the moon orbit first
  • Draw the moon second
  • Draw the shadow third
  • Finally draw the earth.

In this update I did not recalculate the rotation etc. but used save/restore.

var sun = {
    radius	: 80,
    x		: 0,
    y		: 0,
};
var earth = {
    radius	: 20,
    x		: sun.radius + 80,
    y		: 0,
    angle	: 0,
};
var moon = {
    radius	: 8,
    x		: 50,
    y		: 0,
    angle	: 0,
};

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

context.setTransform(1,0,0,1,canvas.width/2, canvas.height/2);

// sun
context.beginPath();
context.arc(0, 0, sun.radius, 0, 360 * Math.PI/180, false);
context.fillStyle = "yellow";
context.fill();

// sun orbit
context.beginPath();
context.arc(0, 0, earth.x, 0, Math.PI*2, false);
context.strokeStyle = "rgba(180,150,0,.25)";
context.stroke();

canvas.style.backgroundImage = "url(" + canvas.toDataURL() + ")";

function draw() {

    context.setTransform(1,0,0,1,0,0);    
    context.clearRect(0, 0, canvas.width, canvas.height)
    context.setTransform(1,0,0,1,canvas.width/2, canvas.height/2);
    
    // earth
    earth.angle += .2;
    if (earth.angle == 360) {
        earth.angle = 0;
    }
    context.rotate(earth.angle * Math.PI/180);
    context.translate(earth.x, 0);

        // earth orbit
    context.beginPath();
    context.arc(0, 0, moon.x, 0, Math.PI*2, false);
    context.strokeStyle = "rgba(0,0,200,.2)";
    context.stroke();
    
    // moon
    context.save();
    moon.angle += 1;
    if (moon.angle == 360) {
        moon.angle = 0;
    }
    context.rotate(moon.angle * Math.PI/180);
    context.translate(moon.x, 0);
    context.beginPath();
    context.arc(0, 0, moon.radius, 0, 360 * Math.PI/180, false);
    context.fillStyle = "silver";
    context.fill();
    context.restore();

    // earth shadow
    context.fillStyle = "rgba(0,0,0,0.1)";
    context.fillRect(0, -earth.radius, earth.radius*16, earth.radius*2);

    context.beginPath();
    context.arc(0, 0, earth.radius, 0, 360*(Math.PI/180), false);
    context.fillStyle = "royalblue";
    context.fill();
    
    
    requestAnimationFrame(draw);
}

draw();
html {
    background: rgb(230,230,230);
}
canvas {
    background: white;
    border: 1px solid rgba(0,0,0,.2);
    box-shadow: 0 0 5px rgba(0,0,0,.1);
}
    <canvas id="canvas" width="640" height="480"></canvas>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!