如何使用特定文件名保存画布图像

时间:2016-01-10 10:44:28

标签: javascript html canvas

我有一个可以显示直播的网页,然后可以快照实时直播。

我需要一个按钮,可以使用我自己的特定文件名将图像保存在画布中(可以是今天的日期)。

非常需要它。感谢那些会回应的人! :)

以下是代码:

<!DOCTYPE html>
<html>
<head>
<title>Video Live Stream</title>
<link rel="stylesheet" type="text/css" href="demo'.css"/>
</head>
<body>
<center>
<style>
    <p>
    video { border: 20px solid #ccc; display: block; margin: 0 0 -5px 0; }
    #canvas { margin-top: 20px; border: 1px solid #ccc; display: block; }

    </p>
</style>
</br>
<h3>Live Stream with Snap Shot</h3>
<div align="center">
    <video style="position:relative;top:-75px;" id="video" width="600" height="600" autoplay="">
    </video>
</div>
<div align="center">
<button style="position:relative;top:-60px;" id="snap" class="sexyButton">Snap Photo</button>
<canvas style="position:relative;top:-60px;" class="input" id="canvas" width="640" height="480"></canvas>

</div>
<a href="#" id="downloader" onclick="$filename">Download!</a>
<script>

    // Put event listeners into place
    window.addEventListener("DOMContentLoaded", function() {
        // Grab elements, create settings, etc.
        var canvas = document.getElementById("canvas"),
            context = canvas.getContext("2d"),
            video = document.getElementById("video"),
            videoObj = { "video": true },
            errBack = function(error) {
                console.log("Video capture error: ", error.code); 
            };
        // Put video listeners into place
        if(navigator.getUserMedia) { // Standard
            navigator.getUserMedia(videoObj, function(stream) {
                video.src = stream;
                video.play();
            }, errBack);
        } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
            navigator.webkitGetUserMedia(videoObj, function(stream){
                video.src = window.webkitURL.createObjectURL(stream);
                video.play();
            }, errBack);
        } else if(navigator.mozGetUserMedia) { // WebKit-prefixed
            navigator.mozGetUserMedia(videoObj, function(stream){
                video.src = window.URL.createObjectURL(stream);
                video.play();
            }, errBack);
        }
        // Trigger photo take
        document.getElementById("snap").addEventListener("click", function() {
            context.drawImage(video, 0, 0, 640, 480);
        });

    }, false);
</script>
</center>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

自动下载文件

您无法保证文件名,但可以建议使用文件名。客户端可能会覆盖文件名,因为它只是一个下载请求,并受客户端下载策略的约束。如果用户允许使用名称保存文件的事件,如果文件存在于下载目录中,则可以通过附加到文件名(或其他内容取决于浏览器)来更改名称。

这是一个简单的下载图像功能。它将尝试将(通过下载)保存到客户端的文件系统,将图像保存为具有给定文件名的PNG。将拍摄图像或画布图像。

<强>更新

正如markE所指出的,所有浏览器都不支持我用来设置文件名的下载属性。因此,只有支持该属性的浏览器才能设置下载名称。

如果不支持MouseEvent对象,也不会下载给定的函数。我为旧浏览器添加了遗留方法fireEvent,即IE,否则该函数将无法下载。

<!DOCTYPE html>
<html>
  <head>
  <script src="scripts/jquery.js" type="text/javascript"></script>
  <link href='https://fonts.googleapis.com/css?family=Comfortaa|Poiret+One' rel='stylesheet' type='text/css'> <!--Google fonts-->
  <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'> <!--Google fonts-->
  <link rel=stylesheet href="scripts/AlbaCSS.css" type="text/css" />
   <title>Alba</title>
   </head>
   <body>

<div id="container">
<div id="console">
<p id="message_begin">Welcome to Alba. At any time you may type "help". Also try using 'pickup [itemname]' to collect items.</p>

<p id="area_main">Alba finds herself at the opening of a forest. Visability is low but she can see paths: 'north', 'east', 'west' and also a 'gate'. On the floor there is a key slightly hidden under a pile of leaves.</p>

<p id="message_help" style="display:none;">Help: <br />
<i>A</i><br />
<i>list</i><br />
<i>of</i><br />
<i>commands</i><br />
<i>would</i><br />
<i>appear</i> </p>

</div>

<!-- ALLOWS CONTENT TO BE INSERTED BEFORE THIS -->
<div id="placeholder"></div>
</div>

<!-- INPUT -->
<form onsubmit="return false;">
<center><input type="text" id="command_line" size="50" autofocus="autofocus" /></center>
</form>
</div>

<script type="text/javascript" src="scripts/game.js"></script>


</body> 
</html>




    // JavaScript Document

// Variables for the game
var inhand = "nothing"; //For picking up items
var lifepoints = 1; //How many lives Alba has

$(document).ready(function() {
    $("#message_begin").fadeIn(3000);
    $("#area_main").fadeIn(3000);
    $("#command_line").fadeIn(3000);
    $("form").submit(function() {
        var input = $("#command_line").val();

        //help
        if (input.indexOf("help") > -1) {
            if (input == "help") {
                $("#message_help").clone().insertBefore("#placeholder").fadeIn(1000);
            }
        }
        //end help


        //pickup
        else if (input == "pickup") {
                $('<p>pickup what? Be specific. Type "help" for a list of all commands.</p>').insertBefore("#placeholder").fadeIn(1000);
            }

            //key
            else if (input == "pickup key") {
                    $('<p>You picked up the key.</p>').insertBefore("#placeholder").fadeIn(1000);
                    inhand = "key";
            }

            //torch
            else if (input == "pickup torch") {
                    $('<p>You picked up the torch.</p>').insertBefore("#placeholder").fadeIn(1000);
                    inhand = "torch";
            }

            //inhand
            else if (input == "inhand") {
                    $('<p>You are currently holding a </p>' + inhand ).insertBefore("#placeholder").fadeIn(1000);
            }


        else if (input != "") {
            $('<p>I don\'t understand "' + input + '"</p>').insertBefore("#placeholder").fadeIn(1000);
        }

        $("#console").scrollTop($("#console")[0].scrollHeight);
        $("#command_line").val("");
});
}); 

使用功能

function saveAsPNG(image, filename){ // No IE <11 support. Chrome URL bug for large images may crash
    var anchorElement, event, blob;
    function image2Canvas(image){  // converts an image to canvas
        function createCanvas(width, height){  // creates a canvas of width height
            var can = document.createElement("canvas");
            can.width = width;
            can.height = height;
            return can;
        };
        var newImage = canvas(img.width, img.height); // create new image
        newImage.ctx = newImage.getContext("2d");  // get image context
        newImage.ctx.drawImage(image, 0, 0); // draw the image onto the canvas
        return newImage;  // return the new image
    }
    if(image.toDataURL === undefined){    // does the image have the toDataURL function
        image = image2Canvas(image);  // No then convert to canvas
    }
    // if msToBlob and msSaveBlob then use them to save. IE >= 10
    // As suggested by Kaiido 
    if(image.msToBlob !== undefined && navigator.msSaveBlob !== undefined){ 
       blob = image.msToBlob(); 
       navigator.msSaveBlob(blob, filename + ".png"); 
       return;
    }
    anchorElement = document.createElement('a');  // Create a download link
    anchorElement.href = image.toDataURL();   // attach the image data URL
    // check for download attribute
    if ( anchorElement.download !== undefined ) {
        anchorElement.download = filename + ".png";  // set the download filename
        if (typeof MouseEvent === "function") {   // does the browser support the object MouseEvent
            event = new MouseEvent(   // yes create a new mouse click event
                "click", {
                    view        : window,
                    bubbles     : true,
                    cancelable  : true,
                    ctrlKey     : false,
                    altKey      : false,
                    shiftKey    : false,
                    metaKey     : false,
                    button      : 0,
                    buttons     : 1,
                }
            );
            anchorElement.dispatchEvent(event); // simulate a click on the download link.
        } else
        if (anchorElement.fireEvent) {    // if no MouseEvent object try fireEvent 
            anchorElement.fireEvent("onclick");
        }
    }
}

这并不保证文件将被保存或文件名将是您想要的。如果要保证文件名,则必须将文件保存在zip文件中。这是很多工作,但仍不保证文件将被保存。安全性要求客户端必须有权接受或拒绝任何下载请求。没有办法支持这一步。

答案 1 :(得分:-2)

我刚刚找到了一种用自己的文件名保存画布图像的方法。你可以在

找到它
http://eligrey.com/demos/FileSaver.js/

编辑画布部分:

<section id="image-demo">
 <form id="canvas-options">
 <label>Filename: <input type="text" class="filename" id="canvas-filename" placeholder="filename"/>.png</label>
        <input type="submit" value="Save"/>
        <input type="button" id="canvas-clear" value="Clear"/>
</form>

并插入以下脚本:

<script type="application/ecmascript" async="" src="Blob.js"/>
<script type="application/ecmascript" async="" src="canvas-toBlob.js"/>
<script type="application/ecmascript" async="" src="FileSaver.js"/>
<script type="application/ecmascript">

有效!