Javascript 如何为html5画布创建jQuery函数

Javascript 如何为html5画布创建jQuery函数,javascript,jquery,html,canvas,html5-canvas,Javascript,Jquery,Html,Canvas,Html5 Canvas,将简单的画布视为 $(document).ready(function(){ draw(); }); function draw() { var canvas = document.getElementById("canvas"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); ctx.fillStyle = "rgb(200,0,0)";

将简单的画布视为

$(document).ready(function(){
draw();
});
    function draw() {  
      var canvas = document.getElementById("canvas");  
      if (canvas.getContext) {  
        var ctx = canvas.getContext("2d");  

        ctx.fillStyle = "rgb(200,0,0)";  
        ctx.fillRect (10, 10, 55, 50);  

        ctx.fillStyle = "rgba(0, 0, 200, 0.5)";  
        ctx.fillRect (30, 30, 55, 50);  
      }  
    }
如何将变量引入jQuery函数,以使用已定义的变量(例如颜色集)绘制多个画布

事实上,我想用
draw(variables)
提供的变量替换canvas id及其选项(如颜色),例如
draw(canvas\u id,color,…)

示例:(用于在不同DOM元素上创建多个画布)

试试这个:

function draw(id, clr, fill) {  
      var canvas = document.getElementById(id);  
      if (canvas.getContext) {  
        var ctx = canvas.getContext("2d");  

        ctx.fillStyle = clr;  
        ctx.fillRect (fill);  

      }  
    }

以下是一种方法:

function draw(colors) {  
  var canvas = document.getElementById("canvas");  
  if (canvas.getContext) {  
    var ctx = canvas.getContext("2d");  

      for(var i=0; i < colors.length; i ++){
          ctx.fillStyle = colors[i];  
          ctx.fillRect (10*i, 10*i, 55, 50);
      } 
  }  
}

// define some colors in an array
var colors = ["rgb(200,0,0)","rgba(0, 0, 200, 0.5)","rgba(0, 128, 200, 0.5)"];

draw(colors);
函数绘制(颜色){
var canvas=document.getElementById(“canvas”);
if(canvas.getContext){
var ctx=canvas.getContext(“2d”);
对于(变量i=0;i
编辑


这是你到底想要什么?如果您的draw()在全局范围内,您可以只使用一些全局变量,为什么还要费心将变量引入
$(document).ready(function(){draw();})?@xiaoyi我希望避免在文档中的每个新画布上重复整个代码。我想要一个带变量的函数。然后,对于每个画布,我需要定义
draw(变量列表)
那么参数从何而来?这是手动定义的,根据上下文计算的吗?@xiaoyi我添加了一个例子来说明我的意思。主要参数是canvas_id。@xiaoyi我明白你关于
$(文档)的观点。准备好了(function(){
),谢谢你的解释。
function draw(colors) {  
  var canvas = document.getElementById("canvas");  
  if (canvas.getContext) {  
    var ctx = canvas.getContext("2d");  

      for(var i=0; i < colors.length; i ++){
          ctx.fillStyle = colors[i];  
          ctx.fillRect (10*i, 10*i, 55, 50);
      } 
  }  
}

// define some colors in an array
var colors = ["rgb(200,0,0)","rgba(0, 0, 200, 0.5)","rgba(0, 128, 200, 0.5)"];

draw(colors);