如何为html5 canvas创建一个jQuery函数

时间:2012-05-19 17:28:38

标签: javascript jquery html5 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)";  
        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_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);

2 个答案:

答案 0 :(得分: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);  

      }  
    }

答案 1 :(得分: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 example