答案 0 :(得分:1)
将draw-all-orbit和draw-all-bodies代码放在可重复使用的函数中
function drawAllOrbits(){
ctx.strokeStyle='black';
for(var i=0;i<orbits.length;i++){
drawOrbit(orbits[i]);
}
}
function drawAllBodies(){
for(var i=0;i<circles.length;i++){
drawOrbitingCircle(circles[i]);
}
}
为您的按钮添加ID
<button id='theButton'>Click</button>
听取按钮上的点击事件。
$('#theButton').on('click',function(){ ... });
单击时,清除画布并按所需顺序重绘场景。
$('#theButton').on('click',function(){
ctx.clearRect(0,0,cw,ch);
circle();
ovarlay();
drawAllOrbits();
drawAllBodies();
});
示例代码和演示:
// vars for canvas
var canvas= document.getElementById('canvas'),
ctx= canvas.getContext('2d'),
cw=canvas.width,
ch=canvas.height,
cx=cw/2,
cy=ch/2;
// vars for orbits & circle-bodies
var circleRadius=12;
var orbits=[80,130];
var circleCountByOrbit=[5,8];
var circles=[];
// flag to indicate which scene to display
var highlightTomato=true;
// calc semi-random orbiting bodies
for(var o=0;o<orbits.length;o++){
var count=circleCountByOrbit[o];
var sweep=Math.PI*2/count;
for(var c=0;c<count;c++){
var midAngle=(sweep*c)+sweep/2;
var randomOffset=Math.random()*0.50-1;
var angle=midAngle+sweep*randomOffset;
circles.push({orbitIndex:o, angle:angle});
}
}
// draw the initial scene
drawHighlightedTomato();
// listen for button click and toggle the scene
$('#theButton').on('click',function(){
ctx.clearRect(0,0,cw,ch);
highlightTomato=!highlightTomato;
if(highlightTomato){
drawHighlightedTomato();
}else{
drawHighlightedBodies();
}
});
///////////////////////////////
// functions to draw scenes
///////////////////////////////
function drawHighlightedTomato(){
drawAllOrbits();
drawAllBodies();
ovarlay();
circle();
}
function drawHighlightedBodies(){
circle();
ovarlay();
drawAllOrbits();
drawAllBodies();
}
function drawOrbit(radius){
ctx.beginPath();
ctx.arc(cx,cy,radius,0,Math.PI*2);
ctx.stroke();
}
function drawOrbitingCircle(circle){
var x=cx+orbits[circle.orbitIndex]*Math.cos(circle.angle);
var y=cy+orbits[circle.orbitIndex]*Math.sin(circle.angle);
ctx.beginPath();
ctx.arc(x,y,circleRadius,0,Math.PI*2);
ctx.fillStyle='#1bb0e7';
ctx.fill();
ctx.strokeStyle='white';
ctx.stroke();
}
function drawAllOrbits(){
ctx.strokeStyle='black';
for(var i=0;i<orbits.length;i++){
drawOrbit(orbits[i]);
}
}
function drawAllBodies(){
for(var i=0;i<circles.length;i++){
drawOrbitingCircle(circles[i]);
}
}
function circle(place){
ctx.beginPath();
ctx.arc(cx,cy,40,0,100);
ctx.fillStyle='tomato';
ctx.fill();
}
function ovarlay(backgroundOverlay){
ctx.beginPath();
ctx.rect(0, 0, cw, ch);
ctx.fillStyle='rgba(0,0,0,0.8)';
ctx.fill();
//ctx.zindex= 1;
}
body{ background-color:white; }
#canvas{border:1px solid red; margin:0 auto; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id=theButton>Toggle</button><br>
<canvas id="canvas" width="300" height="300"></canvas>