HTML5 Canvas:如何为fillRect设置边框? [英] HTML5 Canvas: How to border a fillRect?

查看:863
本文介绍了HTML5 Canvas:如何为fillRect设置边框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在HTML5中,我想制作一个 fillRect()(带有白色填充颜色)和一个边框 (黑色)。我不想使用 strokeRect(),除非稍后可以填写。我正在制作一个游戏,其中您单击正方形,它们就会改变颜色(比这要复杂得多,但这就是重点所在)。

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>

画布周围的边框仅供参考。
我也可以使用CSS,但目前所有内容都在HTML中。

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

推荐答案

找出要绘制的位置具有宽度和高度的正方形。完成此操作后,只需简单地先画一个更大的正方形即可,该正方形的宽度加2,而高度加2,但中心点相同。因此,您绘制一个更大的正方形,然后在顶部绘制一个普通正方形,这就会给您正方形错觉的感觉

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

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链接: https://jsfiddle.net/jxgw19sh/2/

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

-更新-

drawBorder 中添加一个名为 thickness 的附加参数1,但是您可以在函数中提供厚度的任何其他数字,它将使用value代替1。

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.

这篇关于HTML5 Canvas:如何为fillRect设置边框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆