【问题标题】:set html5 canvas dimensions using variables使用变量设置 html5 画布尺寸
【发布时间】:2014-08-26 16:26:27
【问题描述】:
<canvas id="myCanvas" width="250" height="150">
</canvas>

我不想使用特定的数字(250 x 150),而是想在画布之外设置变量并使用这些变量值,如下所示:

myCanvasWidth = 250
myCanvasHeight = 150
<canvas id="myCanvas width = myCanvasWidth height = myCanvasHeight>
</canvas>

我怎样才能做到这一点? 谢谢。

【问题讨论】:

  • 在 JS 中,获取对画布的引用并设置其宽度/高度属性:

标签: html canvas


【解决方案1】:

您不能直接在网页中创建 Canvas,而是为其创建一个容器并在 JavaScript 中执行其他所有操作:

HTML

<div id = "container"></div>

JavaScript

function Engine(name, width, height)
{
    var that = this, running = false, interval = 0;

    that.name = "";
    that.canvas = null;
    that.scene = new Array();

    that.Init = function(name, width, height)
    {
        that.name = name;
        that.canvas = document.createElement("canvas");
        that.canvas.width = width;
        that.canvas.height = height;
    };

    that.Append = function(id)
    {  
        var el = document.getElementById(id);
        if(el && el.appendChild)
        {
            el.appendChild(that.canvas);
        }
    };

    var Render = function(_callback_)
    { 
        // Clear the screen | For each object of scene render and callback
    };

    var Update = function(_callback_)
    {
        // Compute physics if needed | For each object callback
    };

    that.Run = function(render, _update)
    {
        if(!running)
        {
            running = true;
            interval = setInterval(function(){
                Render(_render);
                Update(_update);
            }, 16);
        }
    };

    that.Clear = function()
    {
        if(!running)
        {
            running = false;
            clearInterval(interval);
        }
    };

    that.Init(name, width, height);
}

/* Exemple */
var app = new Engine("test", 640, 480);

app.Append("container");

app.Run(function render(){
    // render
}, function update(){
    // logic
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多