画布绘制功能

时间:2015-10-31 12:16:29

标签: javascript canvas

我的脚本中有一个工作的画布脚本,但我决定将它们移动到函数和原型中,以便更容易阅读代码并更容易扩展。现在我根本没有图像。

这是加载网站时运行的代码。

$(document).ready(function(){
    //Set width and height of canvas
    var width = $(document).width();
    var height = $(document).height();
    $("#MKslide").css({"width":width+"px","height":height+"px"});

    slideShow = new SlideShow(width, height, "2d");
    slideShow.LoadNextSlide(null);
    slideShow.NextSlide();
});

我在SlideShow构造函数中创建了画布。

function SlideShow(canvasWidth, canvasHeight, dimension){
    //Create canvas
    this.canvas = document.getElementById("MKslide");
    this.canvas.width = canvasWidth;
    this.canvas.height = canvasHeight;
    this.context = this.canvas.getContext(dimension);
    this.image = new Image();
    this.image.onload = function(){
        this.context.drawImage(this.image,0,0,canvasWidth,canvasHeight);
    };

    this.currentSlide;
    this.nextSlide;
}

然后我只用这个功能改变图像。

SlideShow.prototype.NextSlide = function(){
    this.currentSlide = this.nextSlide;
    this.image.src = this.currentSlide.data;
}

变量this.nextSlide从Ajax调用中填充。

1 个答案:

答案 0 :(得分:0)

image.onload函数中,this指的是图像对象,而不是幻灯片对象。

因此.onload中的this.image等同于Slideshow.image.image undefined

相反:

function SlideShow(canvasWidth, canvasHeight, dimension){

    // create a self reference for use in image.onload
    var that=this;

    //Create canvas
    this.canvas = document.getElementById("MKslide");
    this.canvas.width = canvasWidth;
    this.canvas.height = canvasHeight;
    this.context = this.canvas.getContext(dimension);
    this.image = new Image();
    this.image.onload = function(){
        // Here inside the image.onload...
        // ... "that" is your SlideShow object
        // ... "this" is the image object
        that.context.drawImage(this,0,0,canvasWidth,canvasHeight);
    };

    this.currentSlide;
    this.nextSlide;
}