需要使用HTML5 canvas和JavaScript创建循环

时间:2011-04-06 22:42:10

标签: javascript html5 canvas

我正在使用jQuery轮播来显示大型SVG图像的38种不同的放大率/位置。理想情况下,我希望使用某种循环来遍历所有不同的大小,绘制到个人canvas并在我的轮播中的每个li中放置一个。谁能帮助我实现这个目标。这是我试过的:

function drawSlides() {
    for (var i = 1; i <= 38; i++) {

    var currentCanvas = 'myCanvas_' + slideNumber;

    // initialise canvas element

    var canvas_i = document.getElementById('' + currentCanvas + '');
        var context = canvas_i.getContext('2d');

    // position of SVG – these measurements are subject to change!
    var destX_i = -6940;
    var destY_i = -29240;
    var destWidth_i = 9373;
    var destHeight_i = 30000;
    context.drawImage('/path/image.svg', 
       destX_i, destY_i, destWidth_i, destHeight_i);

    // white rectangle background  – these are constant
    var topLeftCornerX_i = 453;               
        var topLeftCornerY_i = -10;
    var width_i = 370;
    var height_i = 480;
    context.beginPath();
    context.rect(topLeftCornerX_i, topLeftCornerY_i, width_i, height_i);
    context.fillStyle = "rgba(255, 255, 255, 1)";
    context.fill();

    // orange vertical line – these elements are constant
    context.moveTo(453, 0);
    context.lineTo(453, 460);
    context.lineWidth = 2;
    context.strokeStyle = "#f5d7cb";
    context.stroke();

    //orange ball  – these are constant
    var centerX_ball_i = 453;
    var centerY_ball_i = 323;
    var radius = 99;
    context.beginPath();
    context.arc(centerX_ball_i, centerY_ball_i, radius, 0, 2 * Math.PI, false);
    var grd_ball_i = context.createLinearGradient(224, 354, 422, 552);
    grd_ball_i.addColorStop(0, "#f5d7cb"); // light orange
    grd_ball_i.addColorStop(1, "#ff4900"); // dark orange
    context.fillStyle = grd_ball_i;
    context.fill();
    }            
};

drawSlides();

1 个答案:

答案 0 :(得分:0)

这应该让你感动:

var numCarouselItems = 38;
var myUL  = document.getElementById('carousel');
var items = myUL.childNodes;
var img = new Image;
img.onload = function(){
  for (var i=0;i<numCarouselItems;++i){
    // Find the nth li, or create it
    var li = items[i] || myUL.appendChild(document.createElement('li'));

    // Find the nth canvas, or create it
    var canvas = li.getElementsByTagName('canvas')[0] ||
                 li.appendChild(document.createElement('canvas'));
    canvas.width  =   1; // Erase the canvas, in case it existed
    canvas.width  = 320; // Set the width and height as desired
    canvas.height = 240;
    var ctx = canvas.getContext('2d');

    // Use your actual calculations for the SVG size/position here
    ctx.drawImage( img, 0, 0 );
  }
}

// Be sure to set your image source after your load handler is in place
img.src = "foo.svg";