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


this might obvious alot of people im trying design game want rectangle player different colour walls. how colour them differently? right set ctx.fillstyle colour rectangles. question want rect1 lightgray , rect2 red have tried.also still need rectangles 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() 

your there!

enter image description here

just add fill , stroke definitions rect objects:

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

then can draw every rect using 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 make "factory" function creates new rect 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 , 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>


Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -