【问题标题】:Generating new canvas dynamically in javascript在javascript中动态生成新画布
【发布时间】:2013-08-14 16:44:22
【问题描述】:

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

这是脚本

//<![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上但是它可以在我的本地主机上运行我完全不知道它,无论如何我需要的是生成函数,我做了但我想我错过了一些东西.. 有任何想法吗?谢谢..

【问题讨论】:

    标签: javascript html canvas drawing


    【解决方案1】:

    下面是我写的一个动态创建画布的函数。

    如果画布已经存在(相同的 ID),则返回该画布。

    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;
    }
    

    【讨论】:

      【解决方案2】:

      更改 jsfiddle 选项

      "onLoad" 
      

      "No Wrap - in <body>"
      

      编辑:也可以在这里查看类似的问题:Uncaught ReferenceError for a function defined in an onload function

      JSFiddle 选项:http://doc.jsfiddle.net/basic/introduction.html#frameworks-and-extensions

      【讨论】:

      • 对不起,这是干什么用的?
      • 嗯我不担心 jsfiddle 我的主要问题是关于生成函数以动态生成新画布,而不是为 jsfiddle 出汗,无论如何,谢谢..
      • 问题是:“我想动态生成画布”。如果您在 JSFiddle 中运行代码时查看控制台,则永远不会调用函数“generate()”。通过切换 JSFiddle 选项,您不仅有一个附加到文档的画布,而且还有第一个画布中的工作绘图(它不会在第二个画布上工作,因为它与用于绘图调用的上下文不同) .
      【解决方案3】:

      这是您的 JSFIDDLE 的工作更新

      javascript:

      document.getElementById('generate').addEventListener('mousedown', generate, false);
      

      我想这就是你想要的。

      我刚刚在 javascript 代码中为您的按钮添加了一个 eventListener。

      P.S.:我还在画布上添加了黑色背景颜色以在白色背景上显示它。

      【讨论】:

      • 我们都回答了这个问题,但是这显然不是他想要的。
      • @Mr_Pouet 我想是的。但问题是一样的。不是吗?
      • 谢谢你们的兴趣我很感激.. 现在出现了一个新问题,我无法绘制新生成的画布。我将整个脚本复制并粘贴到生成函数中,但它不起作用。我该怎么做,有什么建议吗?
      • 这是一个不同的问题。请创建一个新线程。 (如果您愿意,请投一两个赞成票;))
      猜你喜欢
      • 2014-05-17
      • 1970-01-01
      • 2021-12-27
      • 2016-09-02
      • 2014-10-14
      • 2016-08-20
      • 1970-01-01
      • 2019-09-22
      • 2018-06-30
      相关资源
      最近更新 更多