2016-09-21 247 views
0

是否可以为画布赋予背景色?所以当图像被提交时,它会有一个颜色,而不是空白(如果图像不够大)。有没有人有任何想法如何做到这一点?JS - 用背景色填充画布

填充有彩色帆布背景下似乎没有工作

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

这个答案并不在这个例子中 – Admamza

+0

@Admamza工作。再看看......这个答案确实可以用你的例子 - 在'drawImage'之前执行'fillRect'。 :-P – markE

+1

Ofcourse我没有做fillRect!谢谢 – Admamza

回答

0

只需转到的.html文件,并创建一个<style>标签。

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

好努力。您的解决方案将为canvas元素提供背景颜色,但是当画布转换为图像时,背景将不可见。 – markE

0
canvasContext.fillStyle = "white"; 
canvasContext.fillRect(0, 0, canvas.width, canvas.height); 
canvasContext.drawImage(image,xOffset, yOffset, newWidth , newHeight);