0

Is it possible to give the canvas a background colour? So that when the image is submitted it will have a colour rather than be blank (if the image isnt big enough). Does anyone have any ideas on how to do this please?

Filling the canvas context with a colour doesnt seem to work

https://jsfiddle.net/n7xL5c37/1/

var canvas = document.getElementById('canvas');
var image = new Image();
image.src = 'http://placehold.it/300x550';
image.onload = function () {
    var canvasContext = canvas.getContext('2d');
    var wrh = image.width / image.height;
    var newWidth = canvas.width;
    var newHeight = newWidth / wrh;
    if (newHeight > canvas.height) {
                newHeight = canvas.height;
        newWidth = newHeight * wrh;
    }
    var xOffset = newWidth < canvas.width ? ((canvas.width - newWidth) / 2) : 0;
    var yOffset = newHeight < canvas.height ? ((canvas.height - newHeight) / 2) : 0;

    canvasContext.drawImage(image, xOffset, yOffset, newWidth, newHeight);
    canvasContext.fillStyle = "red";
  };
NoDachi
  • 874
  • 4
  • 10
  • 20

2 Answers2

0

Simply go to your .html document, and create a <style> tag.

<head>
    <style>
        canvas{
            background-color: red;
        }
    </style>
</head>
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
adr1Script
  • 109
  • 5
  • Good effort. Your solution will give the canvas element a background color, but when the canvas is converted into an image the background will not be visible. – markE Sep 21 '16 at 19:56
  • precisely this could be beneficial in certain scenarios. For example, stacking images in layers in photoshop with html5 canvas generated contents – danivicario Jan 21 '19 at 12:30
  • I agree with marKE how do i have it when saving from context menu on the browser have the background-color black ? – Jay Mee May 02 '22 at 09:24
0
canvasContext.fillStyle = "white";
canvasContext.fillRect(0, 0, canvas.width, canvas.height);
canvasContext.drawImage(image,xOffset, yOffset, newWidth , newHeight);
NoDachi
  • 874
  • 4
  • 10
  • 20