0

我未能使此代码正常工作:

(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');

})();

function hi(){
var canvas = document.getElementsByTagName('canvas');
var imageData = canvas.toDataURL();
    document.getElementById("his").innerHTML=imageData;
}

这是一段 JavaScript 代码,它divid.canvas

而且,我正在尝试保存图像,并div使用保存idhis图像写入 a 。现在这就是代码停止工作的地方......非常感谢您的帮助,谢谢!:)

4

2 回答 2

2

document.getElementsByTagName('canvas')返回 a NodeList,而不是单个元素。所以使用

function hi(){
    var canvas = document.getElementsByTagName('canvas')[0];
    imageData = canvas ? canvas.toDataURL() : "could not find a <canvas> element";
    document.getElementById("his").textContent = imageData;
}
于 2013-02-26T19:10:09.717 回答
1

图像数据 URL 属于图像src属性。图片没有innerHTML

于 2013-02-26T19:02:44.373 回答