javascript - 使用 Javascript 创建一颗星星并指定背景颜色

标签 javascript html css

我想用Javascript画一颗星星并给它一个背景颜色。这是 jsfiddle :-

http://jsfiddle.net/earnubs/TZasK/

但是红色背景颜色覆盖了整个方形区域,我只想为那颗星星提供背景。

这是 JavaScript :-

var canvas, ctx, length = 15; // length of the star's arm

// grab a reference to the 2d context from canvas element
canvas = document.getElementById("star");
ctx = canvas.getContext("2d");

// move into the middle of the canvas, just to make room
ctx.translate(30, 30);

// initial offset rotation so our star is straight
ctx.rotate((Math.PI * 1 / 10));

// make a point, 5 times
for (var i = 5; i--;) {
    // draw line up
    ctx.lineTo(0, length);
    // move origin to current same location as pen
    ctx.translate(0, length);
    // rotate the drawing board
    ctx.rotate((Math.PI * 2 / 10));
    // draw line down
    ctx.lineTo(0, -length);
    // again, move origin to pen...
    ctx.translate(0, -length);
    // ...and rotate, ready for next arm
    ctx.rotate(-(Math.PI * 6 / 10));
}
// last line to connect things up
ctx.lineTo(0, length);
ctx.closePath();
// stroke the path, you could also .fill()
ctx.stroke();

最佳答案

http://jsfiddle.net/TZasK/464/

在定义 ctx 后使用 ctx.fillStyle = "#f00",并在最后使用 ctx.fill()

关于javascript - 使用 Javascript 创建一颗星星并指定背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38090061/

相关文章:

html - 页脚未正确对齐

jquery - 使用 jQuery 更改除当前单击之外的所有类的 src

javascript - Vue.js 和 Immutable.js

javascript - Instafeed Js - 如何给每张图片不同的尺寸

javascript - 如何使用 Tampermonkey 在 React 应用程序中模拟点击?

css - 更改音频播放器的轨道位置

html - 如果显示器屏幕太大,请管理网页的顶部标题

javascript - 如何在 Service Worker 中使用其他 js 文件?

javascript - 如何将属性添加到 jade 中的脚本标记,例如异步延迟

javascript - chrome 使 div 元素的小方 block 在调整大小时不可见