我正在使用html 5画布并尝试在其上绘制圆圈,但是当我尝试使用循环时,所有内容都消失了 [英] I am working on an html 5 canvas and trying to draw circles on it, but as I trying to use a loop all disappears
本文介绍了我正在使用html 5画布并尝试在其上绘制圆圈,但是当我尝试使用循环时,所有内容都消失了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一切都好,直到我尝试放入for循环(无论我打算使用该循环用于什么)。
All good until I trying to put the for loop in(no matter what I am meant to use the loop for).
<canvas id="MyCanvas" width="400" height="400"
style="border:1px solid #000000;">
</canvas>
<script>
function(){
var c = document.getElementById("MyCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(200,200,200,0,2*Math.PI);
ctx.stroke();
ctx.beginPath();
ctx.arc(200,0,10,0,2*Math.PI);
ctx.stroke();
for(int i=0; i<2; i++){
return i;}
}
</script>
推荐答案
以下是重构的代码:
-
将每个圆定义保存在javascript对象中:
var circle1={x:200,y:200,radius:200};
var circle2={x:200,y:0,radius:10};
将所有圆对象保存为数组:
var circles=[];
circles.push(circle1);
circles.push(circle2);
创建一个从指定的圆对象绘制1个圆的函数:
function drawCircle(circle){
ctx.beginPath();
ctx.arc(circle.x,circle.y,circle.radius,0,2*Math.PI);
ctx.closePath();
ctx.stroke();
}
创建一个遍历数组并绘制的函数所有圈子:
function drawAll(){
for(var i=0;i<circles.length;i++){
drawCircle(circles[i]);
}
}
放在一起...这是一个演示:
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var circles=[];
circles.push({x:200,y:200,radius:200});
circles.push({x:200,y:0,radius:10});
drawAll();
function drawAll(){
for(var i=0;i<circles.length;i++){
drawCircle(circles[i]);
}
}
function drawCircle(circle){
ctx.beginPath();
ctx.arc(circle.x,circle.y,circle.radius,0,2*Math.PI);
ctx.closePath();
ctx.stroke();
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<canvas id="canvas" width=400 height=400></canvas>
这篇关于我正在使用html 5画布并尝试在其上绘制圆圈,但是当我尝试使用循环时,所有内容都消失了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文