<canvas id="myCanvas" width="250" height="150">
</canvas>
我想在我的画布之外设置变量而不是使用特定数字(250乘150),而是沿着以下几行使用这些变量值:
myCanvasWidth = 250
myCanvasHeight = 150
<canvas id="myCanvas width = myCanvasWidth height = myCanvasHeight>
</canvas>
我怎样才能做到这一点? 感谢。
答案 0 :(得分:0)
您无法直接在网页中创建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
});