JS - 用背景颜色填充画布

时间:2016-09-21 16:35:27

标签: javascript html5 canvas

是否可以为画布提供背景颜色?因此,当提交图像时,它将具有颜色而不是空白(如果图像不够大)。有没有人对如何做到这一点有任何想法?

使用颜色填充画布上下文似乎无法正常工作

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";
  };

2 个答案:

答案 0 :(得分:0)

只需转到.html文档,然后创建一个<style>代码。

<head>
    <style>
        canvas{
            background-color: red;
        }
    </style>
</head>

答案 1 :(得分:0)

$1 =~ s!^|\n!\n//!gr