简体   繁体   English

在HTML5画布中生成图像

[英]Generating images in HTML5 canvas

I am experimenting with canvas and I am having some trouble. 我正在尝试帆布,但遇到了一些麻烦。

Please see this codepen: 请参阅此代码笔:

http://codepen.io/JonnyBoggon/pen/YGgKqQ http://codepen.io/JonnyBoggon/pen/YGgKqQ

I would like to generate two (or more potentially) floating images - which collide - like the circles in my codepen. 我想生成两个(或更可能是)浮动图像-发生碰撞-就像我的Codepen中的圆圈一样。 So, exactly as it is now, but with images rather than circles. 因此,与现在完全一样,但是带有图像而不是圆圈。

function makeAmpersands(num) {
      var x, y, vx, vy, r, m, ke, colliding, src;

      for (var i = 0; i < num; i++) {
         x = Math.random() * canvas.width;
         y = Math.random() * canvas.height;
         vx = Math.random() * 1 - .5;
         vy = Math.random() * 1 - .5;
         r = 150;
         m = density * (4 / 3) * Math.PI * Math.pow(r, 3);
         ke = .5 * m * (vx + vx) * (vy + vy);
         colliding = false;
         src = siteURL+'/assets/img/floating-ampersand-1.png';

         B.push(new ampersand(x, y, vx, vy, r, m, ke, colliding, src));
      }
   }

I have no idea how to turn those objects into an image object, with a different src for each. 我不知道如何将那些对象转换为图像对象,每个对象具有不同的src。

Please excuse my lack of knowledge with canvas; 请原谅我缺乏知识的画布; this is my first attempt at creating something. 这是我第一次尝试创造东西。

Any help would be greatly appreciated. 任何帮助将不胜感激。

To load and render images using canvas 2D 使用canvas 2D加载和渲染图像

Create and load image 创建并加载图像

Create an new Image object, assign the src the URL of the image you wish to load. 创建一个新的Image对象,为src分配要加载的图像的URL。 The image will then begin to load. 然后将开始加载图像。 You will not be able to know how long the image may take to load so you need to either wait until the image fires the onload event or if you are sure that the resource will always be available only use the image if its complete property is === true 您将无法知道图像加载所需的时间,因此您需要等待直到图像触发onload事件,或者如果您确定资源始终可用,则仅在图像的complete属性为=== true情况下才使用该图像=== true

As I do not know if your images resource is reliable the code below is a mix of the above method, using the onload event to flag that the image has loaded. 我不知道您的图像资源是否可靠,下面的代码混合了上述方法,使用onload事件标记图像已加载。

var image = new Image(); // a new image object same as <img> tag
image.src = "imageURL";  // the url pointing to the image 
image.onload = function(){ this.ready = true; };  // flag image ready
                                                  // This will not happen until
                                                  // the current code has exited

Draw an image onto the canvas. 在画布上绘制图像。

To render the image use the 2D context function drawImage . 要渲染图像,请使用2D上下文函数drawImage This function has up to 9 arguments many of which are optional. 此函数最多有9个参数,其中许多是可选的。 For full details see MDN drawImage . 有关完整详细信息,请参见MDN drawImage

If you try to render the image before it has loaded then you will of course not see anything. 如果尝试在图像加载之前渲染图像,那么您当然看不到任何东西。 If the image has an error during loading attempting to draw it may throw an error and stop your code from running. 如果在加载过程中图像出错,则尝试绘制图像可能会引发错误并导致代码无法运行。 So always be sure your image is ready and safe to draw. 因此,请务必确保您的图像已准备就绪且可以安全绘制。

From the above image load snippet the following snippet renders the image 从上面的图像加载片段中,以下片段呈现了图像

if(image.ready){   // is it ready
    ctx.drawImage(image,x,y);  // draw image with top left at x,y
}

Loading many images. 正在加载许多图像。

It is inefficient to check the image for ready each time you render it. 每次渲染图像时,检查图像是否准备就绪效率不高。 Once ready it is always so. 一旦准备好,它总是如此。 This answer shows how you can load many images. 该答案说明了如何加载许多图像。 If you have an ongoing animation instead of calling the drawImages function when all images have loaded, call a function that starts the animation, or set a flag to indicate that all images have loaded and are safe to render. 如果正在播放动画,而不是在加载完所有图像后调用drawImages函数,请调用一个启动动画的函数,或设置一个标志以指示所有图像均已加载并且可以安全渲染。

A complete image render function. 完整的图像渲染功能。

The 2D API allows you to draw an image that is scaled, rotated, fade in/out. 2D API允许您绘制缩放,旋转,淡入/淡出的图像。 Rendering a image like this is sometimes called a sprite (From the old 16bit days) 像这样渲染图像有时称为子画面(从过去的16位时代开始)

Function to draw a scaled rotated faded image / sprite with the rotation around its center. 绘制缩放的旋转淡入图像/精灵,并围绕其中心旋转。 x and y are the position on the canvas where the center will be. xy是画布上中心的位置。 scale is 1 for no scale <1 for smaller, and >1 for larger. scale为1表示无比例尺,<1表示较小,> 1表示较大。 rot is the rotation with 0 being no rotation. rot是旋转,0表示不旋转。 Math.PI is 180 deg. Math.PI为180度。 Increasing rot will rotate in a clockwise direction decreasing will rotate the other way. 腐烂增加将沿顺时针方向旋转,腐烂减少将以另一种方式旋转。 alpha will set how transparent the image will be with 0 being invisible and 1 as fully visible. alpha将设置图像的透明度,其中0为不可见,1为完全可见。 Trying to set global alpha with a value outside 0-1 range will result in no change. 尝试将全局Alpha设置为0-1范围之外的值将不会导致更改。 The code below does a check to ensure that alpha is clamped. 下面的代码进行检查以确保固定了alpha。 If you trust the alpha value you can set globalAlpha directly 如果您信任alpha值,则可以直接设置globalAlpha

function drawSprite(image,x,y,scale,rot,alpha){
     ctx.setTransform(scale,0,0,scale,x,y);
     ctx.rotate(rot);
     ctx.globalAlpha = alpha < 0 ? 0 : alpha > 1 ? 1 : alpha; // if you may have 
                                                              // alpha values outside
                                                              // the normal range
     ctx.drawImage(image,-image.width / 2, -image.height / 2);
}
// usage
drawSprite(image,x,y,1,0,1); // draws image without rotation or scale
drawSprite(image,x,y,0.5,Math.PI/2,0.5); // draws image rotated 90 deg
                                         // scaled to half its size
                                         // and semi transparent

The function leaves the current transform and alpha as is. 该函数保持当前的变换和alpha不变。 If you render elsewhere (not using this function) you need to reset the current state of the 2D context. 如果在其他地方渲染(不使用此功能),则需要重置2D上下文的当前状态。

To default 默认

ctx.setTransform(1,0,0,1,0,0);
ctx.globalAlpha = 1;

To keep the current state use 保持当前状态使用

ctx.save();
// draw all the sprites
ctx.restore();

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

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