Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

javascript - HTML5 Canvas: How to border a fillRect?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can not fill it later without a library. If you want to change something simply redraw. You can use something like that:

ctx.fillStyle = 'blue';
ctx.strokeStyle = 'red';
var fillRect = false;
ctx.rect(20, 20, 150, 100);
if (fillRect) {
  ctx.fill();
}
ctx.stroke();

it will draw only the border, if you change fillRect to true it will be filled. You can update your canvas on every requestAnimationFrame.

But maybe you want to use a library like paper.js. It makes things like clicking on objects much easier and it abstracts draws on canvas to objects you create once and update later, like what you asked for.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...