Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  12] [ 3]  / answers: 1 / hits: 54199  / 8 Years ago, sun, july 3, 2016, 12:00:00

In HTML5, I want to make a fillRect() (with a white fill color) and a border (black). I don't want to use strokeRect() unless I can fill that later. I'm making a game where you click on squares and they change color (it's more complex than that but that's what this focuses on).



<canvas id=canvas1 width=400 height=300 style=border:1px solid #000000;></canvas>
<script>
var c=document.getElementById(canvas1);
var ctx=c.getContext(2d);
ctx.strokeStyle=rgba(0,0,0,1);
ctx.strokeRect(0,0,100,100);
</script>


The border around the canvas is for reference.
I can use CSS too, but currently everything is in HTML.


More From » css

 Answers
25

Work out the position you want to draw the square with the width and height. Once you have done that simply draw a bigger square first which has wider by 2 and higher by 2 but with the same center point. So you draw a square which is bigger and then you draw the normal square on top, this then gives you the illusion of the square has a border



HTML



<canvas id=canvas1 width=400 height=300 style=border:1px solid #000000;></canvas>


CSS



#canvas1{
border: solid 1px black;
}


Javascript



var c=document.getElementById(canvas1);
var ctx=c.getContext(2d);

var rectXPos = 50;
var rectYPos = 50;
var rectWidth = 100;
var rectHeight = 100;

drawBorder(rectXPos, rectYPos, rectWidth, rectHeight)

ctx.fillStyle='#FFF';
ctx.fillRect(rectXPos, rectYPos, rectWidth, rectHeight);

function drawBorder(xPos, yPos, width, height, thickness = 1)
{
ctx.fillStyle='#000';
ctx.fillRect(xPos - (thickness), yPos - (thickness), width + (thickness * 2), height + (thickness * 2));
}


jsfiddle link : https://jsfiddle.net/jxgw19sh/2/



-- Update --



Add an extra parameter to drawBorder called thickness the default value is 1 but you can provide any other number for thickness into the function and it will use value instead of 1.


[#61528] Friday, July 1, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryanulyssesb

Total Points: 91
Total Questions: 105
Total Answers: 102

Location: England
Member since Tue, Sep 8, 2020
4 Years ago
ryanulyssesb questions
Sat, Mar 20, 21, 00:00, 3 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
Mon, Mar 9, 20, 00:00, 4 Years ago
Sun, Jul 7, 19, 00:00, 5 Years ago
;