javascript - 在javascript中动态生成新 Canvas

标签 javascript html canvas drawing

我有一个 Canvas ,我可以绘制东西,我想做的是在单击按钮时动态生成新 Canvas 。我定义了一个生成函数,但它不起作用

这是脚本

//<![CDATA[ 
window.addEventListener('load', function () {
// get the canvas element and its context
var canvas = document.getElementById('sketchpad');
var context = canvas.getContext('2d');

// create a drawer which tracks touch movements
var drawer = {
    isDrawing: false,
    touchstart: function (coors) {
        context.beginPath();
        context.moveTo(coors.x, coors.y);
        this.isDrawing = true;
    },
    touchmove: function (coors) {
        if (this.isDrawing) {
            context.lineTo(coors.x, coors.y);
            context.stroke();
        }
    },
    touchend: function (coors) {
        if (this.isDrawing) {
            this.touchmove(coors);
            this.isDrawing = false;
        }
    }
};
// create a function to pass touch events and coordinates to drawer
function draw(event) { 
    var type = null;
    // map mouse events to touch events
    switch(event.type){
        case "mousedown":
                event.touches = [];
                event.touches[0] = { 
                    pageX: event.pageX,
                    pageY: event.pageY
                };
                type = "touchstart";                  
        break;
        case "mousemove":                
                event.touches = [];
                event.touches[0] = { 
                    pageX: event.pageX,
                    pageY: event.pageY
                };
                type = "touchmove";                
        break;
        case "mouseup":                
                event.touches = [];
                event.touches[0] = { 
                    pageX: event.pageX,
                    pageY: event.pageY
                };
                type = "touchend";
        break;
    }    

    // touchend clear the touches[0], so we need to use changedTouches[0]
    var coors;
    if(event.type === "touchend") {
        coors = {
            x: event.changedTouches[0].pageX,
            y: event.changedTouches[0].pageY
        };
    }
    else {
        // get the touch coordinates
        coors = {
            x: event.touches[0].pageX,
            y: event.touches[0].pageY
        };
    }
    type = type || event.type
    // pass the coordinates to the appropriate handler
    drawer[type](coors);
}

// detect touch capabilities
var touchAvailable = ('createTouch' in document) || ('ontouchstart' in window);

// attach the touchstart, touchmove, touchend event listeners.
if(touchAvailable){
    canvas.addEventListener('touchstart', draw, false);
    canvas.addEventListener('touchmove', draw, false);
    canvas.addEventListener('touchend', draw, false);        
}    
// attach the mousedown, mousemove, mouseup event listeners.
else {
    canvas.addEventListener('mousedown', draw, false);
    canvas.addEventListener('mousemove', draw, false);
    canvas.addEventListener('mouseup', draw, false);
}

// prevent elastic scrolling
document.body.addEventListener('touchmove', function (event) {
    event.preventDefault();
}, false); // end body.onTouchMove

}, false); // end window.onLoad


function generate(){

var newCanvas = document.createElement('canvas');
newCanvas.width = 400;
newCanvas.height = 400;
document.getElementById('container').appendChild(newCanvas);
ctx = newCanvas.getContext('2d');
}

//]]>  

这里是 jsfiddle http://jsfiddle.net/regeme/WVUwn/ ps:绘图未显示在 jsfiddle 上,但它可以在我的本地主机上运行,​​我完全不知道它,无论如何我需要的是生成函数,我做到了,但我认为我错过了一些东西.. 有任何想法吗?谢谢..

最佳答案

下面是我编写的用于动态创建 Canvas 的函数。

如果 Canvas 已存在(相同 ID),则返回该 Canvas 。

pixelRatio 参数可以默认为 1。它用于在 Retina 显示屏上设置正确的尺寸(因此对于配备 Retina 的 iPhone,该值将为 2)

function createLayer(sizeW, sizeH, pixelRatio, id, zIndex) {

    // *** An id must be given.
    if (typeof id === undefined) {
        return false;
    }

    // *** If z-index is less than zero we'll make it a buffer image.
    isBuffer = (zIndex < 0) ? true : false;


    // *** If the canvas exist, clean it and just return that.
    var element = document.getElementById(id);
    if (element !== null) {
        return element;
    }

    // *** If no zIndex is passed in then default to 0.
    if (typeof zIndex === undefined || zIndex < 0) {
        zIndex = 0;
    }

    var canvas = document.createElement('canvas');

    canvas.width = sizeW;
    canvas.height = sizeH;
    canvas.id = id;
    canvas.style.width = sizeW*pixelRatio + "px";
    canvas.style.height = sizeH*pixelRatio + "px";
    canvas.style.position = "absolute";
    canvas.style.zIndex = zIndex;

    if (!isBuffer) {
        var body = document.getElementsByTagName("body")[0];
        body.appendChild(canvas);
    }

    return canvas;
}

关于javascript - 在javascript中动态生成新 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18202795/

相关文章:

jquery - 指定导航栏中所选选项卡的样式

javascript - <button formtarget ="_blank"></button> 不起作用

javascript - 无法让移动导航重新出现

performance - 如何以最佳效率在paperjs中重新定位路径线?

html - 在 HTML5 canvas 中用线性渐变绘制圆弧

javascript - 使用 "pencil"在 Canvas 上绘图

javascript - 注入(inject) jQuery 不起作用

javascript - 游戏关卡的数据结构

javascript - Window.open + href 替换并弹出到新窗口但不使用目标_blank

javascript - 向下滚动 html 元素 (<ul>) 就是可见性 :none