2

考虑一个简单的画布作为

$(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 函数中引入变量以使用定义的变量(例如颜色集)绘制多个画布。

事实上,我想用提供的变量替换画布 id 及其选项(如颜色)draw(variables),例如draw(canvas_id, color, ...).

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

    function draw(ccc) {  
      var canvas = document.getElementById(ccc);  
      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);  
      }  
    } 

draw(canvas1);
draw(canvas2);
4

2 回答 2

1

尝试这个:

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

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

      }  
    }
于 2012-05-19T17:36:49.947 回答
1

这是您可以做到的一种方法:

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

编辑

这是jsfiddle示例

于 2012-05-19T17:37:43.320 回答