--- title: CanvasRenderingContext2D.fillRect() slug: Web/API/CanvasRenderingContext2D/fillRect tags: - API - Canvas - CanvasRenderingContext2D - Referencia - metodo translation_of: Web/API/CanvasRenderingContext2D/fillRect ---
O método CanvasRenderingContext2D
.fillRect()
da API Canvas 2D desenha um retângulo preenchido na posição (x, y), no qual o tamanho é determinado pela width (largura) e pela height (altura), e cujo o estilo é determinado pelo atributo fillStyle
.
void ctx.fillRect(x, y, width, height);
x
y
width
height
fillRect
Isto é só um simples trecho de código que usa o método fillRect
.
<canvas id="canvas"></canvas>
var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.fillStyle = 'green'; ctx.fillRect(10, 10, 100, 100); // preenche todo o canvas // ctx.fillRect(0, 0, canvas.width, canvas.height);
Edite o código abaixo e veja as alterações instantâneas no canvas:
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code" class="playable-code"> ctx.fillStyle = "green"; ctx.fillRect(10, 10, 100, 100);</textarea>
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var textarea = document.getElementById("code"); var reset = document.getElementById("reset"); var edit = document.getElementById("edit"); var code = textarea.value; function drawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addEventListener("click", function() { textarea.value = code; drawCanvas(); }); edit.addEventListener("click", function() { textarea.focus(); }) textarea.addEventListener("input", drawCanvas); window.addEventListener("load", drawCanvas);
{{ EmbedLiveSample('Playable_code', 700, 360) }}
Especificação | Estado | Comentário |
---|---|---|
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-fillrect", "CanvasRenderingContext2D.fillRect")}} | {{Spec2('HTML WHATWG')}} |
{{CompatibilityTable}}
Característica | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Suporte básico | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} |
Característica | Android | Chrome para Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|---|
Suporte básico | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} |