javascript - 为什么 Canvas 中的 fill() 属性会被覆盖?

标签 javascript jquery html canvas

我是html5 canvas学习者 当我尝试画2个圆(一个圆中的一个圆)时。 当我画一个圆圈并填充它时,它就起作用了。 当我画第二个圆圈并填充它时。它变成具有第二种填充样式的第一个圆圈。

我尝试创建的是灰色圆圈中的橙色圆圈。 我尝试了很多次来解决这个问题,但每次都会遇到问题..

请检查我的代码,如果我错了或者如何解决此问题,请告诉我。

我有以下代码

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script>
    <style>
body{
}
#mycanvas{
    border:1px solid #000;  
    margin:0px auto;
    display:block;
}
#mycanvas1{
    border:1px solid #000;  
    margin:0px auto;
    display:block;
}
</style>

<body>

<canvas id="mycanvas" width="200" height="200">
    Your browser does not support the HTML5 canvas tag.
</canvas>
<canvas id="mycanvas1" width="200" height="200">
    Your browser does not support the HTML5 canvas tag.
</canvas>
<script type="text/javascript">
    var c = document.getElementById("mycanvas");
    var b = document.getElementById("mycanvas1");
    var d = document.getElementById("mycanvas1");
    var ctx = c.getContext("2d");
    var ctx1 = b.getContext("2d");
    var ctx2 = d.getContext("2d");
    ctx.fillStyle = "#bddfb3";
    ctx.fillRect(0,0,200,200);
    ctx.moveTo(0,0);
    ctx.lineTo(200,200);
    ctx.stroke();

    ctx1.fillStyle = "#f1b147";
    ctx1.arc(100,100,80,0,360);
    ctx1.fill();

    ctx2.fillStyle = "#222";
    ctx2.arc(100,100,50,45,180);
    ctx2.fill();
    ctx1.fillStyle="#fff";
    ctx1.font="72px Arial";
    ctx1.fillText("i",90,125);

</script>

</body>
</html>

最佳答案

这是在 Canvas 上的灰色圆圈内绘制橙色圆圈的简单方法。

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

// orange circle
ctx.beginPath();
// centerX, centerY, radius, start angle, end angle, counterclockwise
ctx.arc(100, 100, 50, 0, 2 * Math.PI, false);
ctx.fillStyle = 'orange';
ctx.fill();

// grey circle
ctx.lineWidth = 25;
ctx.strokeStyle = 'grey';
ctx.stroke();
<canvas id="canvas" width="500" height="250"></canvas>

关于javascript - 为什么 Canvas 中的 fill() 属性会被覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26422281/

相关文章:

php - 从 HTTP PUT 读取数据

javascript - 如何在和 ID 的元素上使用 getElementId

Javascript原型(prototype),如何访问原型(prototype)函数

javascript - Node.appendChild 的 Silverstripe 参数 1 未实现 Node 接口(interface)

javascript - 页面上的多个 slider

javascript - 正则表达式 - 如果模式以//注释开头,则避免匹配

javascript - 是否可以在 Canvas HTML5 中设置背景图像,并可以执行一些绘画功能,如撤消、删除、清除、保存该背景图像?

jquery - 当鼠标悬停在菜单项上时,超链接会移动。

javascript - 替代成百上千的 if 语句

javascript - 使用 Javascript 设置和获取图像属性