HTML5画布,另存为图像,toDataURL(),创建ID

时间:2013-02-26 18:30:25

标签: javascript html5 canvas

我有这个小的JavaScript画布片段:

(function() {
    // Creates a new canvas element and appends it as a child
    // to the parent element, and returns the reference to
    // the newly created canvas element


    function createCanvas(parent, width, height) {
        var canvas = {};
        canvas.node = document.createElement('canvas');
        canvas.context = canvas.node.getContext('2d');
        canvas.node.width = width || 100;
        canvas.node.height = height || 100;
        parent.appendChild(canvas.node);
        return canvas;
    }

    function init(container, width, height, fillColor) {
        var canvas = createCanvas(container, width, height);
        var ctx = canvas.context;
        // define a custom fillCircle method
        ctx.fillCircle = function(x, y, radius, fillColor) {
            this.fillStyle = fillColor;
            this.beginPath();
            this.moveTo(x, y);
            this.arc(x, y, radius, 0, Math.PI * 2, false);
            this.fill();
        };
        ctx.clearTo = function(fillColor) {
            ctx.fillStyle = fillColor;
            ctx.fillRect(0, 0, width, height);
        };
        ctx.clearTo(fillColor || "#ddd");

        // bind mouse events
        canvas.node.onmousemove = function(e) {
            if (!canvas.isDrawing) {
               return;
            }
            var x = e.pageX - this.offsetLeft;
            var y = e.pageY - this.offsetTop;
            var radius = 10; // or whatever
            var fillColor = '#ff0000';
            ctx.fillCircle(x, y, radius, fillColor);
        };
        canvas.node.onmousedown = function(e) {
            canvas.isDrawing = true;
        };
        canvas.node.onmouseup = function(e) {
            canvas.isDrawing = false;
        };
    }

    var container = document.getElementById('canvas');
    init(container, 200, 200, '#ddd');

})();

现在它使用id canvas的div,并在其中创建一个HTML5 canvas,用户基本上可以用鼠标绘制。现在这很好......但如果我必须用canvas.toDataURL()在画布中保存什么呢?据我所知,我必须使用画布,然后执行canvas.toDataURL()将其保存到图像中。但是 - 这需要一个身份证吗? SOOOO当我在createCanvas函数中创建画布时,我如何制作id伴随它,所以我可以做document.getElementById("idofcanvas").toDataURL()之类的事情?

提前感谢您的帮助! :)

1 个答案:

答案 0 :(得分:2)

  

但是 - 这需要一个身份证吗?

它不需要一个ID,但ID不会受到伤害(只要它实际上是唯一的;-))。任何选择DOM元素的方法都可以在这里使用。如果页面上只有一个画布,这就足够了,例如:

var canvas = document.getElementsByTagName('canvas')[0];
var imageData = canvas.toDataURL();
  

当我在createCanvas函数中创建画布时,我如何制作一个伴随它的id?

您只需在返回之前设置canvas元素的ID属性。请记住,您需要确保此值是唯一的!

function createCanvas(parent, width, height) {
    var canvas = {};
    canvas.node = document.createElement('canvas');
    canvas.node.id = /* some unique value here */;
    canvas.context = canvas.node.getContext('2d');
    canvas.node.width = width || 100;
    canvas.node.height = height || 100;
    parent.appendChild(canvas.node);
    return canvas;
}