设置画布作为背景

时间:2015-08-27 07:05:04

标签: javascript canvas html5-canvas

目前我有一个画布图像,可以用JavaScript改变颜色。我试图将它设置为我的背景,然后失败。

我已按照此Google开发者指南进行操作,但似乎过于简单 - https://developers.google.com/web/updates/2012/12/Canvas-driven-background-images?hl=en

这是我的剧本:

<script>
    var ctx = document.getCSSCanvasContext('2d', 'animation', 300, 300);
    var canvas = document.getElementById("canvas");
    var processing = new Processing(canvas, function(processing) {
        processing.size(innerWidth, innerHeight);
        processing.background(0xFFF);

        var mouseIsPressed = false;
        processing.mousePressed = function () { mouseIsPressed = true; };
        processing.mouseReleased = function () { mouseIsPressed = false; };

        var keyIsPressed = false;
        processing.keyPressed = function () { keyIsPressed = true; };
        processing.keyReleased = function () { keyIsPressed = false; };

        function getImage(s) {
            var url = "https://www.kasandbox.org/programming-images/" + s + ".png";
            processing.externals.sketch.imageCache.add(url);
            return processing.loadImage(url);
        }

        with (processing) {

    var Walker = function() {
        this.x = width/2;
        this.y = height/2;
        this.walkSpeed = 10;
        this.r = random(100,255);
        this.g = random(100,255);
        this.b = random(100,255);
        this.colorStep = 5;
    };

Walker.prototype.display = function() {
    noStroke();
    fill(this.r, this.g, this.b);
    ellipse(this.x, this.y, 10, 10);
};

Walker.prototype.changeColor = function() {
    this.r+=(random(0,2)-1)*this.colorStep;
    this.g+=(random(0,2)-1)*this.colorStep;
    this.b+=(random(0,2)-1)*this.colorStep;
};

// Randomly move up, down, left, right, or stay in one place
Walker.prototype.walk = function() {
    var choice = floor(random(4));
    if(this.x<=0||this.x>=width) {
        this.x=width/2;
    }
    if(this.y<=0||this.y>=height) {
        this.y=height/2;
    }
    if (choice === 0) {
        this.x+=this.walkSpeed;
    } else if (choice === 1) {
        this.x-=this.walkSpeed;
    } else if (choice === 2) {
        this.y+=this.walkSpeed;
    } else {
        this.y-=this.walkSpeed;
    } 
};

var w = new Walker();

var draw = function() {
    w.walk();
    w.changeColor();
    w.display();
};

        }
        if (typeof draw !== 'undefined') processing.draw = draw;
    });

</script>

该网站位于http://worldofwinfield.co.uk/

请放轻松 - 我是初学者!

由于 詹姆斯

0 个答案:

没有答案