如何为 html5 canvas 制作 jQuery 函数

How to make a jQuery function for html5 canvas

本文关键字:制作 jQuery 函数 canvas html5      更新时间:2023-09-26

将一个简单的画布视为

$(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)提供的变量替换画布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);

试试这个:

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

编辑

这是jsfiddle示例