因为png图片的背景都是透明的,所以我们可以寻找透明的pixel,然后将其全部设置成白色,核心代码如下:
JavaScript Code复制内容到剪贴板
-
- var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
- for(var i = 0; i < imageData.data.length; i += 4) {
-
- if(imageData.data[i + 3] == 0) {
- imageData.data[i] = 255;
- imageData.data[i + 1] = 255;
- imageData.data[i + 2] = 255;
- imageData.data[i + 3] = 255;
- }
- }
- context.putImageData(imageData, 0, 0);
完整代码如下:
XML/HTML Code复制内容到剪贴板
- <p>Canvas:</p>
- <canvas id="canvas" style="border: 1px solid #ccc;"></canvas>
- <br>
- <p>Base64转码后的图片:</p>
- <div id="base64Img"></div>
-
- <script type="text/javascript">
- var base64Img = document.getElementById("base64Img"),
- canvas = document.getElementById("canvas"),
- context = canvas.getContext("2d");
-
- // 创建新图片
- var img = new Image();
- img.src = "1.png";
-
- img.addEventListener("load", function() {
- // 绘制图片到canvas上
- canvas.width = img.width;
- canvas.height = img.height;
-
- context.drawImage(img, 0, 0);
-
- // 将canvas的透明背景设置成白色
- var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
- for(var i = 0; i < imageData.data.length; i += 4) {
- // 当该像素是透明的,则设置成白色
- if(imageData.data[i + 3] == 0) {
- imageData.data[i] = 255;
- imageData.data[i + 1] = 255;
- imageData.data[i + 2] = 255;
- imageData.data[i + 3] = 255;
- }
- }
- context.putImageData(imageData, 0, 0);
-
- // 展示base64位的图片
- getBase64(canvas, function(dataUrl) {
- var newImg = document.createElement("img");
- newImg.src = dataUrl;
-
- base64Img.appendChild(newImg);
- });
- }, false);
-
- // 获取canvas的base64图片的dataURL(图片格式为image/jpeg)
- function getBase64(canvas, callback) {
- var dataURL = canvas.toDataURL("image/jpeg");
-
- if(typeof callback !== undefined) {
- callback(dataURL);
- }
- }
- </script>
效果如下:
缺点显而易见。当png图片上存在半透明区域时,会将其填充为黑色。这是我们不希望的。
解决方案二:在canvas绘制前填充白色背景