JS -填充画布的背景颜色

JS - Fill canvas with background colour

本文关键字:背景 颜色 填充 JS      更新时间:2023-09-26

是否可以给画布一个背景颜色?因此,当图像提交时,它将有一个颜色,而不是空白(如果图像不够大)。有谁对如何做到这一点有什么想法吗?

用颜色填充画布上下文似乎不起作用

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";
  };
canvasContext.fillStyle = "white";
canvasContext.fillRect(0, 0, canvas.width, canvas.height);
canvasContext.drawImage(image,xOffset, yOffset, newWidth , newHeight);

简单地进入你的。html文档,并创建一个<style>标签。

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