简体   繁体   English

将图像添加到画布

[英]Add image to canvas

I saw on the internet beatiful example of canvas: https://codepen.io/anon/pen/BdjzPb 我在网上看到了画布的美丽示例: https : //codepen.io/anon/pen/BdjzPb

And I became interested in canvas. 我开始对画布感兴趣。 So I began to study it. 所以我开始研究它。 But I can not understand how to change the dots (stars) in this example to pictures? 但是我不明白如何将本示例中的点(星号)更改为图片? I tried different combinations of context.drawImage(...) but I have no results... The question is, where I should insert context.drawImage(...) to replace white dots with my images? 我尝试了context.drawImage(...)不同组合,但没有结果...问题是,我应该在哪里插入context.drawImage(...)来替换图像中的白点? Here is js code of this canvas: 这是此画布的js代码:

 /*
 * requestAnimationFrame pollyfill
 */
if (!window.requestAnimationFrame) {
    window.requestAnimationFrame = (window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (callback) {
        return window.setTimeout(callback, 1000 / 60);
    });
}

// Init Stats
var stats = new Stats();
stats.setMode(0);
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '0px';
document.body.appendChild(stats.domElement);


/*!
 * Mantis.js / jQuery / Zepto.js plugin for Constellation
 * @version 1.2.2
 * @author Acauã Montiel <contato@acauamontiel.com.br>
 * @license http://acaua.mit-license.org/
 */
(function ($, window) {
    /**
     * Makes a nice constellation on canvas
     * @constructor Constellation
     */
    function Constellation (canvas, options) {
        var $canvas = $(canvas),
            context = canvas.getContext('2d'),
            defaults = {
                star: {
                    color: 'rgba(255, 255, 255, .5)',
                    width: 1,
                    randomWidth: true
                },
                line: {
                    color: 'rgba(255, 255, 255, .5)',
                    width: 0.2
                },
                position: {
                    x: 0, // This value will be overwritten at startup
                    y: 0 // This value will be overwritten at startup
                },
                width: window.innerWidth,
                height: window.innerHeight,
                velocity: 0.1,
                length: 100,
                distance: 120,
                radius: 150,
                stars: []
            },
            config = $.extend(true, {}, defaults, options);

        function Star () {
            this.x = Math.random() * canvas.width;
            this.y = Math.random() * canvas.height;

            this.vx = (config.velocity - (Math.random() * 0.5));
            this.vy = (config.velocity - (Math.random() * 0.5));

            this.radius = config.star.randomWidth ? (Math.random() * config.star.width) : config.star.width;
        }

        Star.prototype = {
            create: function(){
                context.beginPath();
                context.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
                context.fill();
            },

            animate: function(){
                var i;
                for (i = 0; i < config.length; i++) {

                    var star = config.stars[i];

                    if (star.y < 0 || star.y > canvas.height) {
                        star.vx = star.vx;
                        star.vy = - star.vy;
                    } else if (star.x < 0 || star.x > canvas.width) {
                        star.vx = - star.vx;
                        star.vy = star.vy;
                    }

                    star.x += star.vx;
                    star.y += star.vy;
                }
            },

            line: function(){
                var length = config.length,
                    iStar,
                    jStar,
                    i,
                    j;

                for (i = 0; i < length; i++) {
                    for (j = 0; j < length; j++) {
                        iStar = config.stars[i];
                        jStar = config.stars[j];

                        if (
                            (iStar.x - jStar.x) < config.distance &&
                            (iStar.y - jStar.y) < config.distance &&
                            (iStar.x - jStar.x) > - config.distance &&
                            (iStar.y - jStar.y) > - config.distance
                        ) {
                            if (
                                (iStar.x - config.position.x) < config.radius &&
                                (iStar.y - config.position.y) < config.radius &&
                                (iStar.x - config.position.x) > - config.radius &&
                                (iStar.y - config.position.y) > - config.radius
                            ) {
                                context.beginPath();
                                context.moveTo(iStar.x, iStar.y);
                                context.lineTo(jStar.x, jStar.y);
                                context.stroke();
                                context.closePath();
                            }
                        }
                    }
                }
            }
        };

        this.createStars = function () {
            var length = config.length,
                star,
                i;

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

            for (i = 0; i < length; i++) {
                config.stars.push(new Star());
                star = config.stars[i];

                star.create();
            }

            star.line();
            star.animate();
        };

        this.setCanvas = function () {
            canvas.width = config.width;
            canvas.height = config.height;
        };

        this.setContext = function () {
            context.fillStyle = config.star.color;
            context.strokeStyle = config.line.color;
            context.lineWidth = config.line.width;
        };

        this.setInitialPosition = function () {
            if (!options || !options.hasOwnProperty('position')) {
                config.position = {
                    x: canvas.width * 0.5,
                    y: canvas.height * 0.5
                };
            }
        };

        this.loop = function (callback) {
            callback();

            window.requestAnimationFrame(function () {
                stats.begin(); // Only for Stats
                this.loop(callback);
                stats.end(); // Only for Stats
            }.bind(this));
        };

        this.bind = function () {
            $canvas.on('mousemove', function(e){
                config.position.x = e.pageX - $canvas.offset().left;
                config.position.y = e.pageY - $canvas.offset().top;
            });
        };

        this.init = function () {
            this.setCanvas();
            this.setContext();
            this.setInitialPosition();
            this.loop(this.createStars);
            this.bind();
        };
    }

    $.fn.constellation = function (options) {
        return this.each(function () {
            var c = new Constellation(this, options);
            c.init();
        });
    };
})($, window);

// Init plugin
$('canvas').constellation({
    star: {
        width: 3
    },
    line: {
        color: 'rgba(255, 0, 0, .5)'
    },
    radius: 250
});

You need to modify the create() method of Star constructor, because this is exactly the one that's being called when the canvas redraws everything (as a part of calling createStars() method inside the loop). 您需要修改Star构造函数的create()方法,因为这正是画布重绘所有内容时(作为在循环内调用createStars()方法的一部分)而被调用的那个方法。

There is, however, one thing about context.drawImage(...) that you should be aware of: it needs image to be present in the DOM in order to render it in canvas, so first you would have to do something like 但是,有关context.drawImage(...)一件事,您应该注意:它需要在DOM中存在图像才能在画布中呈现它,因此首先您必须执行类似的操作

var img = new Image;
img.src = 'https://sourceofyourimage/image.jpg';

and then in create() method you can call context.drawImage(...) passing image, coordinates and size (if you want to). 然后在create()方法中,可以调用context.drawImage(...)传递图像,坐标和尺寸(如果需要)。

https://codepen.io/Alvvi/pen/RZroPW here is a working CodePen https://codepen.io/Alvvi/pen/RZroPW这是一个正常的CodePen

Also, you may want to check, if the image is loaded before trying to paint it, I suggest using onload for that, however in my case it works fine without it, because the image is quite small. 另外,您可能要检查图像是否在尝试绘制之前已加载,我建议为此使用onload ,但是在我的情况下,如果没有图像,它可以正常工作,因为图像很小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM