【问题标题】:How do you colour rectangles different colours using ctx.fill?如何使用 ctx.fill 为矩形着色不同的颜色?
【发布时间】:2014-11-27 14:46:51
【问题描述】:

这对很多人来说可能很明显,但我试图设计一个游戏,我希望矩形播放器的颜色与墙壁不同。我将如何为它们着色?现在我将 ctx.fillstyle 设置为所有矩形的颜色。对于这个问题,我希望 rect1 为浅灰色,而 rect2 为红色,这是我尝试过的。而且我仍然需要我的矩形作为对象。

ctx.fillStyle = "lightgray";
ctx.strokeStyle = "skyblue";
ctx.beginPath()
// Moving Rect 1
var rect1 = {
    x: 125,
    y: 10,
    w: 20,
    h: 20
};
ctx.closePath()
ctx.fill()
var direction1 = 0



ctx.fillStyle = "red";
ctx.strokeStyle = "skyblue";
ctx.beginPath()

var rect2 = {
    x:120,
    y:110,
    w:10,
    h:10
};

ctx.closePath()
ctx.fill()

【问题讨论】:

    标签: javascript html html5-canvas rectangles


    【解决方案1】:

    你快到了!

    只需将填充和描边定义添加到您的矩形对象:

    var rect1 = {
        x: 125,
        y: 10,
        w: 20,
        h: 20,
        fill:'lightgray',
        stroke:'skyblue',
    };
    

    然后你可以使用一个函数来绘制每个矩形:

    drawRect(rect1);
    
    function drawRect(rect){
        ctx.fillStyle=rect.fill;
        ctx.strokeStyle=rect.stroke;
        ctx.fillRect(rect.x,rect.y,rect.w,rect.h);
        ctx.strokeRect(rect.x,rect.y,rect.w,rect.h);    
    }
    

    你甚至可以创建一个“工厂”函数,用你给定的定义创建一个新的矩形:

    var grayRect=createRect(125,10,20,20,'lightgray','skyblue');
    var redRect=createRect(120,110,10,10,'red','skyblue');
    
    function createRect(x,y,width,height,fill,stroke){
        return({
            x:x,
            y:y,
            w:width,
            h:height,
            fill:fill,
            stroke:stroke
        });
    }
    

    示例代码和演示:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    
    var grayRect=createRect(125,10,20,20,'lightgray','skyblue');
    var redRect=createRect(120,110,10,10,'red','skyblue');
    
    drawRect(grayRect);
    drawRect(redRect);
    
    
    function createRect(x,y,width,height,fill,stroke){
      return({
        x:x,y:y,
        width:width,height:height,
        fill:fill,stroke:stroke
      });
    }
    
    function drawRect(rect){
      ctx.fillStyle=rect.fill;
      ctx.strokeStyle=rect.stroke;
      ctx.fillRect(rect.x,rect.y,rect.width,rect.height);
      ctx.strokeRect(rect.x,rect.y,rect.width,rect.height);    
    }
    body{ background-color: ivory; padding:10px; }
    #canvas{border:1px solid red;}
    <canvas id="canvas" width=300 height=300></canvas>

    【讨论】:

    • 感谢您的回答!你知道如何以这种方式改变矩形的不透明度/alpha 吗?
    • 不客气!要控制矩形的 alpha,您可以将 alpha 属性分配给矩形对象(例如,alpha:0.50,)。然后在drawRect 中,您可以在绘制矩形之前更改ctx.globalAlpha=rect.alpha;。绘制矩形后,请务必通过重置ctx.globalAlpha=1.00 来“清理”。祝你的项目好运!
    猜你喜欢
    • 2013-02-26
    • 1970-01-01
    • 2016-04-03
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多