画布,移动物体,javascript中的clearRect

时间:2014-02-02 09:17:11

标签: javascript canvas

基本上,我的问题是我无法理解为什么我在代码中使用的函数clearRect不会清除矩形(为了使它们移动我使用setinterval函数)。我有正在移动的矩形。

在设置间隔功能中,您可以看到我试图在循环之前放置的context.clearRect(0, 0, context.elem.width, context.elem.height);(不起作用)和循环(相同:()。可以修复此问题吗?!任何帮助表示赞赏。谢谢

window.onload = function () {

    function Shape(x, y, w, h, fill) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.fill = fill;
    }

    // get canvas element.
    var elem = document.getElementById('paper');
    context = elem.getContext('2d');
    //var container = {x:100, y:100, width:1200, height: 800};
    context.fillStyle = "black";
    context.fillRect(0, 0, elem.width, elem.height);


    // check if context exist
    if (elem.getContext) {

        var array = [];

        array.push(new Shape(20, 0, 50, 50, "red"));
        array.push(new Shape(20, 60, 50, 50, "red"));
        array.push(new Shape(20, 120, 50, 50, "red"));
        array.push(new Shape(80, 0, 50, 50, "red"));
        array.push(new Shape(80, 60, 50, 50, "red"));
        array.push(new Shape(80, 120, 50, 50, "red"));
        array.push(new Shape(140, 0, 50, 50, "red"));
        array.push(new Shape(140, 60, 50, 50, "red"));
        array.push(new Shape(140, 120, 50, 50, "red"));
        //context = elem.getContext('2d');
    }

    //function draw (){
    // context.fillStyle = 'red'; 
    //context.fillRect(container.x, container.y, container.width, container,height);
    //}

    setInterval(function () {

        /// clear canvas for each frame
        //context.clearRect(0, 0, context.elem.width, context.elem.height);

        /// iterate object array and move all objects
        for (var i = 0, oRec; oRec = array[i]; i++) {
            // context.clearRect(0, 0, context.elem.width, context.elem.height);

            oRec.x++; /// update each object's position
            context.beginPath();
            context.fillStyle = oRec.fill;
            context.fillRect(oRec.x, oRec.y, oRec.w, oRec.h);
            context.fill();

        }
    }, 40);
};

1 个答案:

答案 0 :(得分:1)

请尝试使用此内容,因为上下文中没有elem属性:

context.clearRect(0, 0, context.canvas.width, context.canvas.height);

或直接使用elem(写入速度更快,也更短):

context.clearRect(0, 0, elem.width, elem.height);

<强> Fiddle 1

clearRect()在画布上清除所有,包括填充背景(默认情况下,画布元素是透明的,并且在使用clearRect()时将处于初始状态或再次变为<)。< / p>

使用黑色clearRect()fillRect()替换为fillStyle,或者为元素设置CSS背景(如果需要,后者将不会与任何图像一起保存,即。toDataURL())。

黑色背景:

<强> Fiddle 2 using CSS background

<强> Fiddle 3 using fillRect instead of clearRect

您可以通过仅清除方框来进一步优化fillRect()(因为它比clearRect()慢)(请记住在每侧添加一个像素用于消除锯齿的像素)。

相关问题