'canvas tag produces black block in chrome
This is very frustrating. If I don't set the height and width of the canvas, canvas draws just fine, but when I do set the height and width I get back a black box. I've stripped my code down to an insane degree and can't find any problem. The canvas tag works great in FF and IE9.
var canvas = document.getElementById('can1');
var ctx = canvas.getContext('2d');
canvas.width = 280;
canvas.height = 270;
ctx.clearRect(0, 0, canvas.width, canvas.height);
Even just this destroys the canvas in google chrome. No matter how little I draw, if the height or width is set it fails. If I set the height or width with css instead, it produces a distorted result.
Any ideas?
UPDATE: I've discovered that if my canvas is small enough, it works in chrome. However I need a canvas that is 280x270 not 100x100
Solution 1:[1]
Another solution I found that may help a very small number of people is that Chrome is more specific with context.fillStyle compared to other browsers. The hex color code prefix # is required in Chrome in this situation.
Here is one method of adjusting the entire canvas background color to a solid color:
const canvas = document.querySelector('canvas'); // Selects the DOM's first canvas element
const context = canvas.getContext('2d'); // Look into the canvas context documentation
context.fillStyle = '#2f2f2f'; // Gives us a nice dark gray color
context.fillRect(0, 0, canvas.width, canvas.height); // Fills the entire canvas
I would like to add that it is good practice to always include # when using hex color codes. Just an old silly mistake I noticed when I looked back on an old project of mine.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ethan McRae |
