CodeNoob
CodeNoob

Reputation: 45

How do you colour rectangles different colours using ctx.fill?

This might be very obvious to alot of people but im trying to design a game where I want the rectangle player a different colour than the walls. How would I colour them differently? right now what i set ctx.fillstyle to is the colour for all rectangles. For this question I want rect1 to be lightgray and rect2 to be red this what I have tried.Also I still need my rectangles to be objects.

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()

Upvotes: 0

Views: 732

Answers (1)

markE
markE

Reputation: 105015

Your almost there!

enter image description here

Just add the fill and stroke definitions to your rect objects:

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

Then you can draw every rect using just a single function:

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);    
}

You can even make a "factory" function that creates a new rect with your given definitions:

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
    });
}

Example code and a Demo:

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>

Upvotes: 2

Related Questions